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/4/0xC9492c6eD66e1D4DF46f99742e6485acC4BdD3ea/sources/contracts/MyDropContract.sol
|
Determine what wallet can update claim conditions
|
function _canSetClaimConditions() internal override returns (bool){
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
| 710,144
|
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------
// Based on code by OpenZeppelin
// ----------------------------------------------------------------------
// Copyright (c) 2016 Smart Contract Solutions, Inc.
// Released under the MIT license
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/LICENSE
// ----------------------------------------------------------------------
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to 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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(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;
MintFinished();
return true;
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
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);
}
}
contract TkoToken is MintableToken, BurnableToken, PausableToken {
string public constant name = 'TkoToken';
string public constant symbol = 'TKO';
uint public constant decimals = 18;
}
/// @title Whitelist for TKO token sale.
/// @author Takeoff Technology OU - <info@takeoff.ws>
/// @dev Based on code by OpenZeppelin's WhitelistedCrowdsale.sol
contract TkoWhitelist is Ownable{
using SafeMath for uint256;
// Manage whitelist account address.
address public admin;
mapping(address => uint256) internal totalIndividualWeiAmount;
mapping(address => bool) internal whitelist;
event AdminChanged(address indexed previousAdmin, address indexed newAdmin);
/**
* TkoWhitelist
* @dev TkoWhitelist is the storage for whitelist and total amount by contributor's address.
* @param _admin Address of managing whitelist.
*/
function TkoWhitelist (address _admin) public {
require(_admin != address(0));
admin = _admin;
}
/**
* @dev Throws if called by any account other than the owner or the admin.
*/
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || msg.sender == admin);
_;
}
/**
* @dev Allows the current owner to change administrator account of the contract to a newAdmin.
* @param newAdmin The address to transfer ownership to.
*/
function changeAdmin(address newAdmin) public onlyOwner {
require(newAdmin != address(0));
emit AdminChanged(admin, newAdmin);
admin = newAdmin;
}
/**
* @dev Returen whether the beneficiary is whitelisted.
*/
function isWhitelisted(address _beneficiary) external view onlyOwnerOrAdmin returns (bool) {
return whitelist[_beneficiary];
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwnerOrAdmin {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrAdmin {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwnerOrAdmin {
whitelist[_beneficiary] = false;
}
/**
* @dev Return total individual wei amount.
* @param _beneficiary Addresses to get total wei amount .
* @return Total wei amount for the address.
*/
function getTotalIndividualWeiAmount(address _beneficiary) external view onlyOwnerOrAdmin returns (uint256) {
return totalIndividualWeiAmount[_beneficiary];
}
/**
* @dev Set total individual wei amount.
* @param _beneficiary Addresses to set total wei amount.
* @param _totalWeiAmount Total wei amount for the address.
*/
function setTotalIndividualWeiAmount(address _beneficiary,uint256 _totalWeiAmount) external onlyOwner {
totalIndividualWeiAmount[_beneficiary] = _totalWeiAmount;
}
/**
* @dev Add total individual wei amount.
* @param _beneficiary Addresses to add total wei amount.
* @param _weiAmount Total wei amount to be added for the address.
*/
function addTotalIndividualWeiAmount(address _beneficiary,uint256 _weiAmount) external onlyOwner {
totalIndividualWeiAmount[_beneficiary] = totalIndividualWeiAmount[_beneficiary].add(_weiAmount);
}
}
/// @title TKO Token Sale contract.
/// @author Takeoff Technology OU - <info@takeoff.ws>
contract TkoTokenSale is FinalizableCrowdsale, Pausable {
using SafeMath for uint256;
uint256 public initialRate;
uint256 public finalRate;
uint256 public limitEther;
uint256 public largeContribThreshold;
uint256 public largeContribPercentage;
TkoWhitelist internal whitelist;
/**
* TkoTokenSale
* @dev TkoTokenPresale sells tokens at a set rate for the specified period.
* Tokens that can be purchased per 1 Ether will decrease linearly over the period.
* Bonus tokens are issued for large contributor at the rate specified.
* If you wish to purchase above the specified amount, you need to be registered in the whitelist.
* @param _openingTime Opening unix timestamp for TKO token pre-sale.
* @param _closingTime Closing unix timestamp for TKO token pre-sale.
* @param _initialRate Number of tokens issued at start (minimum unit) per 1wei.
* @param _finalRate Number of tokens issued at end (minimum unit) per 1wei.
* @param _limitEther Threshold value of purchase amount not required to register in whitelist (unit Ether).
* @param _largeContribThreshold Threshold value of purchase amount in which bonus occurs (unit Ether)
* @param _largeContribPercentage Percentage of added bonus
* @param _wallet Wallet address to store Ether.
* @param _token The address of the token to be sold in the pre-sale. TkoTokenPreSale must have ownership for mint.
* @param _whitelist The address of the whitelist.
*/
function TkoTokenSale (
uint256 _openingTime,
uint256 _closingTime,
uint256 _initialRate,
uint256 _finalRate,
uint256 _limitEther,
uint256 _largeContribThreshold,
uint256 _largeContribPercentage,
address _wallet,
TkoToken _token,
TkoWhitelist _whitelist
)
public
Crowdsale(_initialRate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
{
initialRate = _initialRate;
finalRate = _finalRate;
limitEther = _limitEther;
largeContribThreshold = _largeContribThreshold;
largeContribPercentage = _largeContribPercentage;
whitelist = _whitelist;
}
/**
* @dev Extend parent behavior to confirm purchase amount and whitelist.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen whenNotPaused {
uint256 limitWeiAmount = limitEther.mul(1 ether);
require( whitelist.isWhitelisted(_beneficiary) ||
whitelist.getTotalIndividualWeiAmount(_beneficiary).add(_weiAmount) < limitWeiAmount);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/**
* @dev Returns the rate of tokens per wei at the present time.
* Note that, as price _increases_ with time, the rate _decreases_.
* @return The number of tokens a buyer gets per wei at a given time
*/
function getCurrentRate() public view returns (uint256) {
uint256 elapsedTime = now.sub(openingTime);
uint256 timeRange = closingTime.sub(openingTime);
uint256 rateRange = initialRate.sub(finalRate);
return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange));
}
/**
* @dev Overrides parent method taking into account variable rate and add bonus for large contributor.
* @param _weiAmount The value in wei to be converted into tokens
* @return The number of tokens _weiAmount wei will buy at present time
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentRate = getCurrentRate();
uint256 tokenAmount = currentRate.mul(_weiAmount);
uint256 largeContribThresholdWeiAmount = largeContribThreshold.mul(1 ether);
if ( _weiAmount >= largeContribThresholdWeiAmount ) {
tokenAmount = tokenAmount.mul(largeContribPercentage).div(100);
}
return tokenAmount;
}
/**
* @dev Add wei amount to the address's amount on the whitelist contract.
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
whitelist.addTotalIndividualWeiAmount(_beneficiary, _weiAmount);
super._updatePurchasingState(_beneficiary, _weiAmount);
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal onlyWhileOpen whenNotPaused {
// Don't call super._deliverTokens() to transfer token.
// Following call will mint FOR _beneficiary, So need not to call transfer token .
require(TkoToken(token).mint(_beneficiary, _tokenAmount));
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pauseCrowdsale() public onlyOwner whenNotPaused {
TkoToken(token).pause();
super.pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpauseCrowdsale() public onlyOwner whenPaused {
TkoToken(token).unpause();
super.unpause();
}
/**
* @dev called by the owner to change owner of token and whitelist.
*/
function evacuate() public onlyOwner {
TkoToken(token).transferOwnership(wallet);
whitelist.transferOwnership(wallet);
}
/**
* @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 {
TkoToken(token).transferOwnership(wallet);
whitelist.transferOwnership(wallet);
super.finalization();
}
}
|
Returen whether the beneficiary is whitelisted./
|
function isWhitelisted(address _beneficiary) external view onlyOwnerOrAdmin returns (bool) {
return whitelist[_beneficiary];
}
| 1,268,430
|
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) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Invalid 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), "Zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract EyeToken is ERC20, Ownable {
using SafeMath for uint256;
struct Frozen {
bool frozen;
uint until;
}
string public name = "EYE Token";
string public symbol = "EYE";
uint8 public decimals = 18;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
mapping(address => Frozen) public frozenAccounts;
uint256 internal totalSupplyTokens;
bool internal isICO;
address public wallet;
function EyeToken() public Ownable() {
wallet = msg.sender;
isICO = true;
totalSupplyTokens = 10000000000 * 10 ** uint256(decimals);
balances[wallet] = totalSupplyTokens;
}
/**
* @dev Finalize ICO
*/
function finalizeICO() public onlyOwner {
isICO = false;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupplyTokens;
}
/**
* @dev Freeze account, make transfers from this account unavailable
* @param _account Given account
*/
function freeze(address _account) public onlyOwner {
freeze(_account, 0);
}
/**
* @dev Temporary freeze account, make transfers from this account unavailable for a time
* @param _account Given account
* @param _until Time until
*/
function freeze(address _account, uint _until) public onlyOwner {
if (_until == 0 || (_until != 0 && _until > now)) {
frozenAccounts[_account] = Frozen(true, _until);
}
}
/**
* @dev Unfreeze account, make transfers from this account available
* @param _account Given account
*/
function unfreeze(address _account) public onlyOwner {
if (frozenAccounts[_account].frozen) {
delete frozenAccounts[_account];
}
}
/**
* @dev allow transfer tokens or not
* @param _from The address to transfer from.
*/
modifier allowTransfer(address _from) {
require(!isICO, "ICO phase");
if (frozenAccounts[_from].frozen) {
require(frozenAccounts[_from].until != 0 && frozenAccounts[_from].until < now, "Frozen account");
delete frozenAccounts[_from];
}
_;
}
/**
* @dev transfer tokens 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) {
bool result = _transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return result;
}
/**
* @dev transfer tokens for a specified address in ICO mode
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferICO(address _to, uint256 _value) public onlyOwner returns (bool) {
require(isICO, "Not ICO phase");
require(_to != address(0), "Zero address 'To'");
require(_value <= balances[wallet], "Not enought balance");
balances[wallet] = balances[wallet].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(wallet, _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];
}
/**
* @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 allowTransfer(_from) returns (bool) {
require(_value <= allowed[_from][msg.sender], "Not enought allowance");
bool result = _transfer(_from, _to, _value);
if (result) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
}
return result;
}
/**
* @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;
}
/**
* @dev transfer token for a specified address
* @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 allowTransfer(_from) returns (bool) {
require(_to != address(0), "Zero address 'To'");
require(_from != address(0), "Zero address 'From'");
require(_value <= balances[_from], "Not enought balance");
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
return true;
}
}
/**
* @title Crowd-sale
*
* @dev Crowd-sale contract for tokens
*/
contract CrowdSale is Ownable {
using SafeMath for uint256;
event Payment(
address wallet,
uint date,
uint256 amountEth,
uint256 amountCoin,
uint8 bonusPercent
);
uint constant internal MIN_TOKEN_AMOUNT = 5000;
uint constant internal SECONDS_IN_DAY = 86400; // 24 * 60 * 60
uint constant internal SECONDS_IN_YEAR = 31557600; // ( 365 * 24 + 6 ) * 60 * 60
int8 constant internal PHASE_NOT_STARTED = -5;
int8 constant internal PHASE_BEFORE_PRESALE = -4;
int8 constant internal PHASE_BETWEEN_PRESALE_ICO = -3;
int8 constant internal PHASE_ICO_FINISHED = -2;
int8 constant internal PHASE_FINISHED = -1;
int8 constant internal PHASE_PRESALE = 0;
int8 constant internal PHASE_ICO_1 = 1;
int8 constant internal PHASE_ICO_2 = 2;
int8 constant internal PHASE_ICO_3 = 3;
int8 constant internal PHASE_ICO_4 = 4;
int8 constant internal PHASE_ICO_5 = 5;
address internal manager;
EyeToken internal token;
address internal base_wallet;
uint256 internal dec_mul;
address internal vest_1;
address internal vest_2;
address internal vest_3;
address internal vest_4;
int8 internal phase_i; // see PHASE_XXX
uint internal presale_start = 1533020400; // 2018-07-31 07:00 UTC
uint internal presale_end = 1534316400; // 2018-08-15 07:00 UTC
uint internal ico_start = 1537254000; // 2018-09-18 07:00 UTC
uint internal ico_phase_1_days = 7;
uint internal ico_phase_2_days = 7;
uint internal ico_phase_3_days = 7;
uint internal ico_phase_4_days = 7;
uint internal ico_phase_5_days = 7;
uint internal ico_phase_1_end;
uint internal ico_phase_2_end;
uint internal ico_phase_3_end;
uint internal ico_phase_4_end;
uint internal ico_phase_5_end;
uint8[6] public bonus_percents = [50, 40, 30, 20, 10, 0];
uint internal finish_date;
uint public exchange_rate; // tokens in one ethereum * 1000
uint256 public lastPayerOverflow = 0;
/**
* @dev Crowd-sale constructor
*/
function CrowdSale() Ownable() public {
phase_i = PHASE_NOT_STARTED;
manager = address(0);
}
/**
* @dev Allow only for owner or manager
*/
modifier onlyOwnerOrManager(){
require(msg.sender == owner || (msg.sender == manager && manager != address(0)), "Invalid owner or manager");
_;
}
/**
* @dev Returns current manager
*/
function getManager() public view onlyOwnerOrManager returns (address) {
return manager;
}
/**
* @dev Sets new manager
* @param _manager New manager
*/
function setManager(address _manager) public onlyOwner {
manager = _manager;
}
/**
* @dev Set exchange rate
* @param _rate New exchange rate
*
* executed by CRM
*/
function setRate(uint _rate) public onlyOwnerOrManager {
require(_rate > 0, "Invalid exchange rate");
exchange_rate = _rate;
}
function _addPayment(address wallet, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent) internal {
emit Payment(wallet, now, amountEth, amountCoin, bonusPercent);
}
/**
* @dev Start crowd-sale
* @param _token Coin's contract
* @param _rate current exchange rate
*/
function start(address _token, uint256 _rate) public onlyOwnerOrManager {
require(_rate > 0, "Invalid exchange rate");
require(phase_i == PHASE_NOT_STARTED, "Bad phase");
token = EyeToken(_token);
base_wallet = token.wallet();
dec_mul = 10 ** uint256(token.decimals());
// Organizasional expenses
address org_exp = 0xeb967ECF00e86F58F6EB8019d003c48186679A96;
// Early birds
address ear_brd = 0x469A97b357C2056B927fF4CA097513BD927db99E;
// Community development
address com_dev = 0x877D6a4865478f50219a20870Bdd16E6f7aa954F;
// Special coins
address special = 0x5D2C58e6aCC5BcC1aaA9b54B007e0c9c3E091adE;
// Team lock
vest_1 = 0x47997109aE9bEd21efbBBA362957F1b20F435BF3;
vest_2 = 0xd031B38d0520aa10450046Dc0328447C3FF59147;
vest_3 = 0x32FcE00BfE1fEC48A45DC543224748f280a5c69E;
vest_4 = 0x07B489712235197736E207836f3B71ffaC6b1220;
token.transferICO(org_exp, 600000000 * dec_mul);
token.transferICO(ear_brd, 1000000000 * dec_mul);
token.transferICO(com_dev, 1000000000 * dec_mul);
token.transferICO(special, 800000000 * dec_mul);
token.transferICO(vest_1, 500000000 * dec_mul);
token.transferICO(vest_2, 500000000 * dec_mul);
token.transferICO(vest_3, 500000000 * dec_mul);
token.transferICO(vest_4, 500000000 * dec_mul);
exchange_rate = _rate;
phase_i = PHASE_BEFORE_PRESALE;
_updatePhaseTimes();
}
/**
* @dev Finalize ICO
*/
function _finalizeICO() internal {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
phase_i = PHASE_ICO_FINISHED;
uint curr_date = now;
finish_date = (curr_date < ico_phase_5_end ? ico_phase_5_end : curr_date).add(SECONDS_IN_DAY * 10);
}
/**
* @dev Finalize crowd-sale
*/
function _finalize() internal {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
uint date = now.add(SECONDS_IN_YEAR);
token.freeze(vest_1, date);
date = date.add(SECONDS_IN_YEAR);
token.freeze(vest_2, date);
date = date.add(SECONDS_IN_YEAR);
token.freeze(vest_3, date);
date = date.add(SECONDS_IN_YEAR);
token.freeze(vest_4, date);
token.finalizeICO();
token.transferOwnership(base_wallet);
phase_i = PHASE_FINISHED;
}
/**
* @dev Finalize crowd-sale
*/
function finalize() public onlyOwner {
_finalize();
}
function _calcPhase() internal view returns (int8) {
if (phase_i == PHASE_FINISHED || phase_i == PHASE_NOT_STARTED)
return phase_i;
uint curr_date = now;
if (curr_date >= ico_phase_5_end || token.balanceOf(base_wallet) == 0)
return PHASE_ICO_FINISHED;
if (curr_date < presale_start)
return PHASE_BEFORE_PRESALE;
if (curr_date <= presale_end)
return PHASE_PRESALE;
if (curr_date < ico_start)
return PHASE_BETWEEN_PRESALE_ICO;
if (curr_date < ico_phase_1_end)
return PHASE_ICO_1;
if (curr_date < ico_phase_2_end)
return PHASE_ICO_2;
if (curr_date < ico_phase_3_end)
return PHASE_ICO_3;
if (curr_date < ico_phase_4_end)
return PHASE_ICO_4;
return PHASE_ICO_5;
}
function phase() public view returns (int8) {
return _calcPhase();
}
/**
* @dev Recalculate phase
*/
function _updatePhase(bool check_can_sale) internal {
uint curr_date = now;
if (phase_i == PHASE_ICO_FINISHED) {
if (curr_date >= finish_date)
_finalize();
}
else
if (phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED) {
int8 new_phase = _calcPhase();
if (new_phase == PHASE_ICO_FINISHED && phase_i != PHASE_ICO_FINISHED)
_finalizeICO();
else
phase_i = new_phase;
}
if (check_can_sale)
require(phase_i >= 0, "Bad phase");
}
/**
* @dev Update phase end times
*/
function _updatePhaseTimes() internal {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
if (phase_i < PHASE_ICO_1)
ico_phase_1_end = ico_start.add(SECONDS_IN_DAY.mul(ico_phase_1_days));
if (phase_i < PHASE_ICO_2)
ico_phase_2_end = ico_phase_1_end.add(SECONDS_IN_DAY.mul(ico_phase_2_days));
if (phase_i < PHASE_ICO_3)
ico_phase_3_end = ico_phase_2_end.add(SECONDS_IN_DAY.mul(ico_phase_3_days));
if (phase_i < PHASE_ICO_4)
ico_phase_4_end = ico_phase_3_end.add(SECONDS_IN_DAY.mul(ico_phase_4_days));
if (phase_i < PHASE_ICO_5)
ico_phase_5_end = ico_phase_4_end.add(SECONDS_IN_DAY.mul(ico_phase_5_days));
if (phase_i != PHASE_ICO_FINISHED)
finish_date = ico_phase_5_end.add(SECONDS_IN_DAY.mul(10));
_updatePhase(false);
}
/**
* @dev Send tokens to the specified address
*
* @param _to Address sent to
* @param _amount_coin Amount of tockens
* @return excess coins
*
* executed by CRM
*/
function transferICO(address _to, uint256 _amount_coin) public onlyOwnerOrManager {
_updatePhase(true);
uint256 remainedCoin = token.balanceOf(base_wallet);
require(remainedCoin >= _amount_coin, "Not enough coins");
token.transferICO(_to, _amount_coin);
if (remainedCoin == _amount_coin)
_finalizeICO();
}
/**
* @dev Default contract function. Buy tokens by sending ethereums
*/
function() public payable {
_updatePhase(true);
address sender = msg.sender;
uint256 amountEth = msg.value;
uint256 remainedCoin = token.balanceOf(base_wallet);
if (remainedCoin == 0) {
sender.transfer(amountEth);
_finalizeICO();
} else {
uint8 percent = bonus_percents[uint256(phase_i)];
uint256 amountCoin = calcTokensFromEth(amountEth);
assert(amountCoin >= MIN_TOKEN_AMOUNT);
if (amountCoin > remainedCoin) {
lastPayerOverflow = amountCoin.sub(remainedCoin);
amountCoin = remainedCoin;
}
base_wallet.transfer(amountEth);
token.transferICO(sender, amountCoin);
_addPayment(sender, amountEth, amountCoin, percent);
if (amountCoin == remainedCoin)
_finalizeICO();
}
}
function calcTokensFromEth(uint256 ethAmount) internal view returns (uint256) {
uint8 percent = bonus_percents[uint256(phase_i)];
uint256 bonusRate = uint256(percent).add(100);
uint256 totalCoins = ethAmount.mul(exchange_rate).div(1000);
uint256 totalFullCoins = (totalCoins.add(dec_mul.div(2))).div(dec_mul);
uint256 tokensWithBonusX100 = bonusRate.mul(totalFullCoins);
uint256 fullCoins = (tokensWithBonusX100.add(50)).div(100);
return fullCoins.mul(dec_mul);
}
/**
* @dev Freeze the account
* @param _accounts Given accounts
*
* executed by CRM
*/
function freeze(address[] _accounts) public onlyOwnerOrManager {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
uint i;
for (i = 0; i < _accounts.length; i++) {
require(_accounts[i] != address(0), "Zero address");
require(_accounts[i] != base_wallet, "Freeze self");
}
for (i = 0; i < _accounts.length; i++) {
token.freeze(_accounts[i]);
}
}
/**
* @dev Unfreeze the account
* @param _accounts Given accounts
*/
function unfreeze(address[] _accounts) public onlyOwnerOrManager {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
uint i;
for (i = 0; i < _accounts.length; i++) {
require(_accounts[i] != address(0), "Zero address");
require(_accounts[i] != base_wallet, "Freeze self");
}
for (i = 0; i < _accounts.length; i++) {
token.unfreeze(_accounts[i]);
}
}
/**
* @dev get ICO times
* @return presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end
*/
function getTimes() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) {
return (presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end);
}
/**
* @dev Sets start and end dates for pre-sale phase_i
* @param _presale_start Pre-sale sart date
* @param _presale_end Pre-sale end date
*/
function setPresaleDates(uint _presale_start, uint _presale_end) public onlyOwnerOrManager {
_updatePhase(false);
require(phase_i == PHASE_BEFORE_PRESALE, "Bad phase");
// require(_presale_start >= now);
require(_presale_start < _presale_end, "Invalid presale dates");
require(_presale_end < ico_start, "Invalid dates");
presale_start = _presale_start;
presale_end = _presale_end;
}
/**
* @dev Sets start date for ICO phases
* @param _ico_start ICO start date
* @param _ico_1_days Days of ICO phase 1
* @param _ico_2_days Days of ICO phase 2
* @param _ico_3_days Days of ICO phase 3
* @param _ico_4_days Days of ICO phase 4
* @param _ico_5_days Days of ICO phase 5
*/
function setICODates(uint _ico_start, uint _ico_1_days, uint _ico_2_days, uint _ico_3_days, uint _ico_4_days, uint _ico_5_days) public onlyOwnerOrManager {
_updatePhase(false);
require(phase_i != PHASE_FINISHED && phase_i != PHASE_ICO_FINISHED && phase_i < PHASE_ICO_1, "Bad phase");
require(presale_end < _ico_start, "Invalid dates");
ico_start = _ico_start;
ico_phase_1_days = _ico_1_days;
ico_phase_2_days = _ico_2_days;
ico_phase_3_days = _ico_3_days;
ico_phase_4_days = _ico_4_days;
ico_phase_5_days = _ico_5_days;
_updatePhaseTimes();
}
}
|
transfer tokens for a specified address in ICO mode _to The address to transfer to. _value The amount to be transferred./
|
function transferICO(address _to, uint256 _value) public onlyOwner returns (bool) {
require(isICO, "Not ICO phase");
require(_to != address(0), "Zero address 'To'");
require(_value <= balances[wallet], "Not enought balance");
balances[wallet] = balances[wallet].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(wallet, _to, _value);
return true;
}
| 5,403,599
|
./partial_match/42/0x9266D722f9F559D3a9588BB21579AED5f058b297/sources/AMMExchange.sol
|
Sets or unsets the approval of a given operator. An operator is allowed to transfer all tokens of the sender on their behalf. Because an account already has operator privileges for itself, this function will revert if the account attempts to set the approval status for itself. operator address to set the approval approved representing the status of the approval to be set/
|
function setApprovalForAll(address operator, bool approved) external {
require(msg.sender != operator, "ERC1155: cannot set approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
@param account The account of the Tokens
@param operator Address of authorized operator
@return True if the operator is approved, false if not
| 3,418,251
|
./full_match/43113/0xb007167714e2940013EC3bb551584130B7497E22/sources/contracts/StablePoolFactory.sol
|
invariant D = invariant D^(n+1) A = amplification coefficient A n^n S + D = A D n^n + ----------- S = sum of balances n^n P P = product of balances n = number of tokens We support rounding up or down.
|
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal virtual returns (uint256);
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal virtual returns (uint256);
}
pragma solidity ^0.7.0;
}
pragma solidity ^0.7.0;
) internal pure returns (uint256) {
uint256 sum = 0;
uint256 numTokens = balances.length;
for (uint256 i = 0; i < numTokens; i++) {
sum = sum.add(balances[i]);
}
if (sum == 0) {
return 0;
}
uint256 prevInvariant = 0;
uint256 invariant = sum;
uint256 ampTimesTotal = amplificationParameter * numTokens;
for (uint256 i = 0; i < 255; i++) {
uint256 P_D = balances[0] * numTokens;
for (uint256 j = 1; j < numTokens; j++) {
P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp);
}
prevInvariant = invariant;
invariant = Math.div(
Math.mul(Math.mul(numTokens, invariant), invariant).add(
Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp)
),
Math.mul(numTokens + 1, invariant).add(
),
roundUp
);
if (invariant > prevInvariant) {
if (invariant - prevInvariant <= 1) {
return invariant;
}
return invariant;
}
}
_revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE);
}
| 7,200,808
|
./full_match/4/0xE2Cf956C80D6477eA8752ED6CC79c49C0DF81483/sources/browser/masterchef.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public{
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 hydgReward = multiplier.mul(hydgPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
hydg.mint(devaddr, hydgReward.div(10));
hydg.mint(address(this), hydgReward);
pool.accHydgPerShare = pool.accHydgPerShare.add(hydgReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 808,316
|
./full_match/3/0x565061dE7Fb334e4C3Dea92deFa76F64B3744763/sources/IERC20Test.sol
|
alıcı adresi ve gönderilecek token miktarı.
|
function transfer(address recipient,uint256 amount)external returns (bool);
| 8,283,107
|
./full_match/42220/0xb37Bf97A42eee6b995732530595E3d16639D9977/sources/contracts/Payroll.sol
|
Celo does not use V3
|
function _performSwapV3ETH(
uint256 _totalAmountToSwap,
uint32 _deadline,
SwapV3[] calldata _swaps
) internal {
require(msg.value >= _totalAmountToSwap, "Payroll: Not enough msg.value");
address weth = IUniswapV3(swapRouter).WETH9();
for (uint256 i = 0; i < _swaps.length; i++) {
require(_swaps[i].path.length > 0, "Payroll: Empty path");
require(_swaps[i].path.toAddress(_swaps[i].path.length - 20) == weth, "Payroll: Swap not native token");
IUniswapV3.ExactOutputParams({
path: _swaps[i].path,
recipient: msg.sender,
deadline: _deadline,
amountOut: _swaps[i].amountOut,
amountInMaximum: _swaps[i].amountInMax
})
);
emit SwapFinished(address(0), _swaps[i].path.toAddress(0), amountIn);
}
}
| 16,339,944
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract Realm is ERC721, ERC721Enumerable, IERC721Receiver, ReentrancyGuard {
address private _creator;
uint256 public SUPPLY_INDEX = 1;
uint256 public SUPPLY_LIMIT = 1;
uint256 public PRICE = 0;
uint256 public GENERATION = 0;
uint256 public constant MAX_SUPPLY = 8088;
uint256 public constant CREATOR_RESERVED = 1011;
uint256 public constant MAX_CLAIM = 8;
uint256 public constant MAX_EDGES = 6;
uint256 public constant MAX_CONTENTS = 16;
// IPFS hash
string[MAX_SUPPLY] public cellDescriptionIds;
uint256[MAX_SUPPLY] public cellGenerations;
CellContent[MAX_CONTENTS][MAX_SUPPLY] public cellContents;
uint256[MAX_EDGES][MAX_SUPPLY] public edges;
uint256[MAX_EDGES][MAX_SUPPLY] public edgesOffered;
mapping (uint256 => EdgeOfferFrom[]) public edgeOffersReceived;
struct CellContent {
address contractAddress;
uint256 tokenId;
address sealOwner;
uint256 sealValue;
}
struct EdgeOfferFrom {
uint256 fromCellIndex;
uint256 fromEdgeIndex;
}
string[] public terrainTypes = [
"Mountain",
"Grassland",
"River",
"Jungle",
"Lake",
"Sea",
"Cave",
"Desert",
"Forest",
"Tundra",
"Swamp"
];
constructor() ERC721("Realm", "R") {
_creator = _msgSender();
// Remove token 0 from supply so edges to 0 work as null
_safeMint(address(this), 0);
_burn(0);
}
function increaseSupply(uint256 additional, uint256 price) external {
require(msg.sender == _creator);
require(SUPPLY_INDEX == SUPPLY_LIMIT, "Limit not reached");
require(SUPPLY_LIMIT + additional <= MAX_SUPPLY - CREATOR_RESERVED, "Max supply");
PRICE = price;
GENERATION += 1;
SUPPLY_LIMIT += additional;
}
// Mint a cell
function claimNext(address to, uint256 count) external payable nonReentrant {
require(SUPPLY_INDEX + count <= SUPPLY_LIMIT, "Count too high");
require(count <= MAX_CLAIM, "Count too high");
require(msg.value >= PRICE * count, "Value too low");
for (uint i=0; i<count; i++) {
cellGenerations[SUPPLY_INDEX] = GENERATION;
_safeMint(to, SUPPLY_INDEX);
emit CreateCell(SUPPLY_INDEX);
SUPPLY_INDEX += 1;
}
}
function claimCreator(address to, uint256 count) external {
require(msg.sender == _creator);
require(SUPPLY_INDEX >= MAX_SUPPLY - CREATOR_RESERVED);
require(SUPPLY_INDEX + count <= MAX_SUPPLY);
for (uint i=0; i<count; i++) {
cellGenerations[SUPPLY_INDEX] = GENERATION + 1;
_safeMint(to, SUPPLY_INDEX);
emit CreateCell(SUPPLY_INDEX);
SUPPLY_INDEX += 1;
}
}
// Assign an IPFS pointer to a description.
function setCellDescriptionId(uint256 cellIndex, string memory descId) external {
require(cellIndex < SUPPLY_INDEX, "Cell index");
require(msg.sender == ownerOf(cellIndex), "Owner");
cellDescriptionIds[cellIndex] = descId;
emit SetCellDescriptionId(cellIndex, descId);
}
function _contentExists(uint256 cellIndex, uint256 contentIndex) internal view returns (bool) {
return cellContents[cellIndex][contentIndex].sealOwner != address(0);
}
// Stores an nft in this cell. Must approve this contract to spend the nft before calling.
function putContent(uint256 cellIndex, uint256 contentIndex, address contractAddress, uint256 tokenId, uint256 sealValue) external nonReentrant {
require(msg.sender == ownerOf(cellIndex), "Owner");
require(cellIndex < SUPPLY_INDEX, "Cell index");
require(contentIndex < MAX_CONTENTS, "Content index");
require(!_contentExists(cellIndex, contentIndex), "Content already");
IERC721 nft = IERC721(contractAddress);
nft.safeTransferFrom(msg.sender, address(this), tokenId);
cellContents[cellIndex][contentIndex] = CellContent(contractAddress, tokenId, msg.sender, sealValue);
emit PutContent(cellIndex, contractAddress, tokenId, sealValue, msg.sender);
}
function takeContent(uint256 cellIndex, uint256 contentIndex) external payable nonReentrant {
require(msg.sender == ownerOf(cellIndex), "Owner");
require(cellIndex < SUPPLY_INDEX, "Cell index");
require(contentIndex < MAX_CONTENTS , "Content index");
require(_contentExists(cellIndex, contentIndex), "Nothing there");
CellContent memory content = cellContents[cellIndex][contentIndex];
require(msg.value >= content.sealValue, "Value too low");
IERC721 nft = IERC721(content.contractAddress);
nft.safeTransferFrom(address(this), msg.sender, content.tokenId);
cellContents[cellIndex][contentIndex] = CellContent(address(0), 0, address(0), 0);
emit TakeContent(cellIndex, content.contractAddress, content.tokenId, content.sealValue, content.sealOwner, msg.sender);
}
// Connect two cells you own.
function createEdge(uint256 fromCellIndex, uint256 fromEdgeIndex, uint256 toCellIndex, uint256 toEdgeIndex) external {
require(fromCellIndex > 0, "Cell index");
require(fromCellIndex < SUPPLY_INDEX, "Cell index");
require(toCellIndex > 0, "Cell index");
require(toCellIndex < SUPPLY_INDEX, "Cell index");
require(fromEdgeIndex < MAX_EDGES, "Edge index");
require(toEdgeIndex < MAX_EDGES, "Edge index");
require(msg.sender == ownerOf(fromCellIndex), "Owner");
require(msg.sender == ownerOf(toCellIndex), "Owner");
require(edges[fromCellIndex][fromEdgeIndex] == 0, "Edge taken");
require(edges[toCellIndex][toEdgeIndex] == 0, "Edge taken");
_removeEdgeOffer(fromCellIndex, fromEdgeIndex);
edges[fromCellIndex][fromEdgeIndex] = toCellIndex;
edges[toCellIndex][toEdgeIndex] = fromCellIndex;
emit CreateEdge(fromCellIndex, fromEdgeIndex, toCellIndex, toEdgeIndex);
}
// Offer to connect one cell to another.
function offerEdge(uint256 fromCellIndex, uint256 fromEdgeIndex, uint256 toCellIndex) external {
require(fromCellIndex > 0, "Cell index");
require(fromCellIndex < SUPPLY_INDEX, "Cell index");
require(toCellIndex > 0, "Cell index");
require(toCellIndex < SUPPLY_INDEX, "Cell index");
require(fromEdgeIndex < MAX_EDGES, "Edge index");
require(msg.sender == ownerOf(fromCellIndex), "Owner");
require(edges[fromCellIndex][fromEdgeIndex] == 0, "Edge taken");
_removeEdgeOffer(fromCellIndex, fromEdgeIndex);
edgesOffered[fromCellIndex][fromEdgeIndex] = toCellIndex;
uint noffers = edgeOffersReceived[toCellIndex].length;
for (uint256 i = 0; i < noffers; i++) {
if (edgeOffersReceived[toCellIndex][i].fromCellIndex == fromCellIndex && edgeOffersReceived[toCellIndex][i].fromEdgeIndex == fromEdgeIndex) return;
}
edgeOffersReceived[toCellIndex].push(EdgeOfferFrom(fromCellIndex, fromEdgeIndex));
emit OfferEdge(fromCellIndex, fromEdgeIndex, toCellIndex);
}
function withdrawEdgeOffer(uint256 fromCellIndex, uint256 fromEdgeIndex) external {
require(fromCellIndex > 0, "Cell index");
require(fromCellIndex < SUPPLY_INDEX, "Cell index");
require(fromEdgeIndex < MAX_EDGES, "Edge index");
require(msg.sender == ownerOf(fromCellIndex), "Owner");
require(edgesOffered[fromCellIndex][fromEdgeIndex] != 0, "No offer");
_removeEdgeOffer(fromCellIndex, fromEdgeIndex);
emit WithdrawEdgeOffer(fromCellIndex, fromEdgeIndex);
}
function _removeEdgeOffer(uint256 fromCellIndex, uint256 fromEdgeIndex) internal {
if (edgesOffered[fromCellIndex][fromEdgeIndex] < SUPPLY_INDEX && edgesOffered[fromCellIndex][fromEdgeIndex] > 0) {
uint256 toCellIndex = edgesOffered[fromCellIndex][fromEdgeIndex];
edgesOffered[fromCellIndex][fromEdgeIndex] = 0;
uint noffers = edgeOffersReceived[toCellIndex].length;
EdgeOfferFrom[] memory offers = edgeOffersReceived[toCellIndex];
for (uint256 i = 0; i < noffers; i++) {
if (offers[i].fromCellIndex == fromCellIndex && offers[i].fromEdgeIndex == fromEdgeIndex) {
edgeOffersReceived[toCellIndex][i] = edgeOffersReceived[toCellIndex][noffers-1];
edgeOffersReceived[toCellIndex].pop();
return;
}
}
}
}
function acceptEdgeOffer(uint256 fromCellIndex, uint256 fromEdgeIndex, uint256 toCellIndex, uint256 toEdgeIndex) external {
require(fromCellIndex > 0, "Cell index");
require(fromCellIndex < SUPPLY_INDEX, "Cell index");
require(toCellIndex > 0, "Cell index");
require(toCellIndex < SUPPLY_INDEX, "Cell index");
require(fromEdgeIndex < MAX_EDGES, "Edge index");
require(toEdgeIndex < MAX_EDGES, "Edge index");
require(msg.sender == ownerOf(toCellIndex), "Owner");
require(edgesOffered[fromCellIndex][fromEdgeIndex] == toCellIndex, "No offer");
require(edges[toCellIndex][toEdgeIndex] == 0, "Edge taken");
_removeEdgeOffer(fromCellIndex, fromEdgeIndex);
edges[fromCellIndex][fromEdgeIndex] = toCellIndex;
edges[toCellIndex][toEdgeIndex] = fromCellIndex;
emit AcceptEdgeOffer(fromCellIndex, fromEdgeIndex, toCellIndex, toEdgeIndex);
}
function destroyEdge(uint256 cellIndex, uint256 edgeIndex) external {
require(cellIndex > 0, "Cell index");
require(cellIndex < SUPPLY_INDEX, "Cell index");
require(edgeIndex < MAX_EDGES, "Edge index");
require(msg.sender == ownerOf(cellIndex), "Owner");
require(edges[cellIndex][edgeIndex] == 0, "Edge empty");
uint256 toCellIndex = edges[cellIndex][edgeIndex];
uint256 toEdgeIndex;
for (uint i = 0; i < MAX_EDGES; i++) {
if (edges[toCellIndex][i] == cellIndex) toEdgeIndex = i;
}
edges[toCellIndex][toEdgeIndex] = 0;
edges[cellIndex][edgeIndex] = 0;
emit DestroyEdge(toCellIndex, toEdgeIndex, cellIndex, edgeIndex);
}
function withdrawAll() external payable {
require(msg.sender == _creator);
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(_creator, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) internal {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external pure override(IERC721Receiver) returns (bytes4) {
return Realm.onERC721Received.selector;
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
uint256 rterr = uint256(keccak256(abi.encodePacked("TERRAIN", tokenId)));
return Util._tokenURI(tokenId, terrainTypes[rterr % terrainTypes.length]);
}
event CreateCell(uint256 indexed id);
event SetCellDescriptionId(uint256 cellIndex, string descId);
event OfferEdge(uint256 indexed fromCellIndex, uint256 fromEdgeIndex, uint256 indexed toCellIndex);
event WithdrawEdgeOffer(uint256 indexed fromCellIndex, uint256 fromEdgeIndex);
event AcceptEdgeOffer(uint256 indexed fromCellIndex, uint256 fromEdgeIndex, uint256 indexed toCellIndex, uint256 toEdgeIndex);
event CreateEdge(uint256 indexed fromCellIndex, uint256 fromEdgeIndex, uint256 indexed toCellIndex, uint256 toEdgeIndex);
event DestroyEdge(uint256 indexed fromCellIndex, uint256 fromEdgeIndex, uint256 indexed toCellIndex, uint256 toEdgeIndex);
event PutContent(uint256 cellIndex, address indexed contractAddress, uint256 tokenId, uint256 sealValue, address indexed sealOwner);
event TakeContent(uint256 cellIndex, address indexed contractAddress, uint256 tokenId, uint256 sealValue, address indexed sealOwner, address indexed takenBy);
}
library Util {
function _tokenURI(uint256 tokenId, string memory _tt) public pure returns (string memory) {
string[4] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = string(abi.encodePacked('Cell #', toString(tokenId)));
parts[2] = '</text><text x="10" y="40" class="base">';
parts[3] = _tt;
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Cell #', toString(tokenId), '", "description": "This is the REALM. It exists to build upon.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
return string(abi.encodePacked('data:application/json;base64,', json));
}
function toString(uint256 value) public pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) public pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
}
}
|
Assign an IPFS pointer to a description.
|
function setCellDescriptionId(uint256 cellIndex, string memory descId) external {
require(cellIndex < SUPPLY_INDEX, "Cell index");
require(msg.sender == ownerOf(cellIndex), "Owner");
cellDescriptionIds[cellIndex] = descId;
emit SetCellDescriptionId(cellIndex, descId);
}
| 1,103,152
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IBaseFee
interface IBaseFee {
function basefee_global() external view returns (uint256);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: ICurveStrategyProxy
interface ICurveStrategyProxy {
function proxy() external returns (address);
function balanceOf(address _gauge) external view returns (uint256);
function deposit(address _gauge, address _token) external;
function withdraw(
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function withdrawAll(address _gauge, address _token)
external
returns (uint256);
function harvest(address _gauge) external;
function lock() external;
function approveStrategy(address) external;
function revokeStrategy(address) external;
function claimRewards(address _gauge, address _token) external;
}
// Part: IOracle
interface IOracle {
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
}
// Part: IUniV3
interface IUniV3 {
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/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/openzeppelin-contracts@3.1.0/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/openzeppelin-contracts@3.1.0/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: yearn/yearn-vaults@0.4.3/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: yearn/yearn-vaults@0.4.3/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: yearn/yearn-vaults@0.4.3/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: StrategyCurveBase
abstract contract StrategyCurveBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// curve infrastructure contracts
ICurveStrategyProxy public proxy =
ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // Yearn's Updated v4 StrategyProxy
ICurveFi public curve; // Curve Pool, need this for depositing into our curve pool
address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter
// keepCRV stuff
uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points)
uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter
// swap stuff
address internal constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there
IERC20 internal constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 internal constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
string internal stratName; // set our strategy name here
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
return proxy.balanceOf(gauge);
}
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our LP tokens to the proxy and deposit to the gauge if we have any
uint256 _toInvest = balanceOfWant();
if (_toInvest > 0) {
want.safeTransfer(address(proxy), _toInvest);
proxy.deposit(gauge, address(want));
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
// check if we have enough free funds to cover the withdrawal
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _amountNeeded.sub(_wantBal))
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
proxy.withdraw(gauge, address(want), _stakedBal);
}
return balanceOfWant();
}
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(gauge, address(want), _stakedBal);
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Use to update Yearn's StrategyProxy contract as needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = ICurveStrategyProxy(_proxy);
}
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyCurveMIMUST.sol
contract StrategyCurveMIMUST is StrategyCurveBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
uint256 public maxGasPrice; // this is the max gas price we want our keepers to pay for harvests/tends in gwei
// Uniswap stuff
IOracle internal constant oracle =
IOracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff); // this is only needed for strats that use uniV3 for swaps
address internal constant uniswapv3 =
0xE592427A0AEce92De3Edee1F18E0157C05861564;
IERC20 internal constant usdc =
IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 internal constant ust =
IERC20(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD);
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
address _curvePool,
address _gauge,
string memory _name
) public StrategyCurveBase(_vault) {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 7 days; // 7 days in seconds
debtThreshold = 1 * 1e6; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 1_000_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// these are our standard approvals. want = Curve LP token
want.approve(address(proxy), type(uint256).max);
crv.approve(sushiswap, type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// this is the pool specific to this vault, used for depositing
curve = ICurveFi(_curvePool);
// set our curve gauge contract
gauge = address(_gauge);
// set our strategy's name
stratName = _name;
// these are our approvals and path specific to this contract
ust.approve(address(curve), type(uint256).max);
weth.approve(uniswapv3, type(uint256).max);
// set our max gas price
maxGasPrice = 100 * 1e9;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything in the gauge, then harvest CRV from the gauge
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.harvest(gauge);
uint256 _crvBalance = crv.balanceOf(address(this));
// if we claimed any CRV, then sell it
if (_crvBalance > 0) {
// keep some of our CRV to increase our boost
uint256 _sendToVoter =
_crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (keepCRV > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
uint256 _crvRemainder = _crvBalance.sub(_sendToVoter);
// sell the rest of our CRV
if (_crvRemainder > 0) {
_sell(_crvRemainder);
}
// convert our WETH to EURt, but don't want to swap dust
uint256 _wethBalance = weth.balanceOf(address(this));
uint256 _ustBalance = 0;
if (_wethBalance > 0) {
_ustBalance = _sellWethForUST(_wethBalance);
}
// deposit our EURt to Curve if we have any
if (_ustBalance > 0) {
curve.add_liquidity([0, _ustBalance], 0);
}
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
if (_stakedBal > 0) {
// don't bother withdrawing if we don't have staked funds
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _debtOutstanding)
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// Sells our harvested CRV into the selected output.
function _sell(uint256 _amount) internal {
address[] memory crvPath = new address[](2);
crvPath[0] = address(crv);
crvPath[1] = address(weth);
IUniswapV2Router02(sushiswap).swapExactTokensForTokens(
_amount,
uint256(0),
crvPath,
address(this),
block.timestamp
);
}
// Sells our WETH for UST
function _sellWethForUST(uint256 _amount) internal returns (uint256) {
uint256 _ustOutput =
IUniV3(uniswapv3).exactInput(
IUniV3.ExactInputParams(
abi.encodePacked(
address(weth),
uint24(500),
address(usdc),
uint24(500),
address(ust)
),
address(this),
block.timestamp,
_amount,
uint256(1)
)
);
return _ustOutput;
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
// check if the base fee gas price is higher than we allow
if (readBaseFee() > maxGasPrice) {
return false;
}
return super.harvestTrigger(callCostinEth);
}
function readBaseFee() internal view returns (uint256 baseFee) {
IBaseFee _baseFeeOracle = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549);
return _baseFeeOracle.basefee_global();
}
// convert our keeper's eth cost into want
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
uint256 callCostInWant;
if (_ethAmount > 0) {
uint256 callCostInEur =
oracle.ethToAsset(_ethAmount, address(ust), 1800);
callCostInWant = curve.calc_token_amount([0, callCostInEur], true);
}
return callCostInWant;
}
/* ========== SETTERS ========== */
// set the maximum gas price we want to pay for a harvest/tend in gwei
function setGasPrice(uint256 _maxGasPrice) external onlyAuthorized {
maxGasPrice = _maxGasPrice.mul(1e9);
}
}
|
convert our keeper's eth cost into want
|
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
uint256 callCostInWant;
if (_ethAmount > 0) {
uint256 callCostInEur =
oracle.ethToAsset(_ethAmount, address(ust), 1800);
callCostInWant = curve.calc_token_amount([0, callCostInEur], true);
}
return callCostInWant;
}
| 5,740,647
|
./full_match/1/0x874e1B98eb3150530Dc410Bb1512f032AEcf0a27/sources/browser/new_yBXTBService2.sol
|
Prevent ERC20 short address attack _data length is not fixed Mode 0x10: Normal deposit Mode 0xF0: Load reserve tokens Normal deposits for Stake and Redeem Sanity check Credit to caller Stake Staking paused by admin Get allowance Enforce token staking ratio Get minimum common size. Size must be the same Accept BXTB Redeem Get allowance Get minimum common size. Size must be the same Redeem YieldToken and CHIP tokens Can't redeem more than outstanding CHIP Accept YieldToken and CHIP Take YieldToken and CHIP out of circulation outstandingYieldToken and outstandingCHIP must be synchronized at all cost Emit event for change in outstanding supply Pay out equivalent amount of USDT, and send BXTB to Foundation Update pool counters Send back collateral Enforce token redemption ratio Can't take out more BXTB than exists Update counters Send BXTB to foundation Calculate collat ratio Last redeemer: Disburse everything In case contract accumulates more than expected, this clears out the account Hard resets USDT counter. No more outstanding CHIP and YieldTokens Pay out USDT Hard reset BXTB counters Send BXTB to foundation Calculate collat ratio
|
function receiveApproval(address _tokenOwner, uint256 _amount, address _tokenContract, bytes memory _data) public override {
require((msg.data.length == (6 * 32) + 4) && (_data.length == 1), "Input length error");
require(msg.sender == yieldTokenContract ||
msg.sender == CHIPContract ||
msg.sender == BXTBContract, "Unknown caller");
uint8 mode = uint8(_data[0]);
require(mode == 0x10 || mode == 0xE0 || mode == 0xF0, "Mode not accepted");
if(mode == 0x10) {
require(totalSupplyYieldToken == totalSupplyCHIP, "Supply imbalance");
uint wildChip;
if(msg.sender == BXTBContract) {
require(allowStaking == true, "Staking is paused");
uint allowanceUsdt = ERC20_USDT(USDTContract).allowance(_tokenOwner, address(this));
uint allowanceBxtb = _amount;
if(allowanceUsdt <= allowanceBxtb) allowanceBxtb = allowanceUsdt;
else allowanceUsdt = allowanceBxtb;
}
else {
if(bxtbTokenRatio > 0) {
uint allowanceBxtbExpected = allowanceUsdt.mulSafe(bxtbTokenRatio).divSafe(100);
}
}
if(allowanceBxtb > 0) {
ERC20Interface(BXTBContract).transferFrom(_tokenOwner, address(this), allowanceBxtb);
totalPoolBXTB = totalPoolBXTB.addSafe(allowanceBxtb);
}
outstandingCHIP = outstandingCHIP.addSafe(allowanceUsdt);
ERC20Interface(yieldTokenContract).transfer(_tokenOwner, allowanceUsdt);
ERC20Interface(CHIPContract).transfer(_tokenOwner, allowanceUsdt);
else collateralizationRatio = 100;
}
else if(msg.sender == CHIPContract) {
uint allowanceYieldToken = ERC20Interface(yieldTokenContract).allowance(_tokenOwner, address(this));
uint allowanceCHIP = _amount;
uint allowanceSize;
if(allowanceYieldToken <= allowanceCHIP) allowanceSize = allowanceYieldToken;
else allowanceSize = allowanceCHIP;
require(allowanceSize > 0, "Zero redeem");
require((allowanceSize <= outstandingCHIP) && (outstandingCHIP > 0), "Redemption size exceeded");
ERC20Interface(yieldTokenContract).transferFrom(_tokenOwner, address(this), allowanceSize);
ERC20Interface(CHIPContract).transferFrom(_tokenOwner, address(this), allowanceSize);
outstandingYieldToken = outstandingYieldToken.subSafe(allowanceSize);
outstandingCHIP = outstandingCHIP.subSafe(allowanceSize);
emit OutstandingSupplyChanged();
uint shareOfBxtb;
if(outstandingCHIP > 0) {
totalPoolUSDTCollateral = totalPoolUSDTCollateral.subSafe(allowanceSize);
ERC20_USDT(USDTContract).transfer(_tokenOwner, allowanceSize);
else shareOfBxtb = allowanceSize.mulSafe(bxtbTokenRatio).divSafe(100);
if(shareOfBxtb > totalPoolBXTB) shareOfBxtb = totalPoolBXTB;
totalPoolBXTB = totalPoolBXTB.subSafe(shareOfBxtb);
ERC20Interface(BXTBContract).transfer(bxtbFoundation, shareOfBxtb);
wildChip = outstandingCHIP.subSafe(totalPoolCHIPBackStop);
else collateralizationRatio = 100;
}
else {
outstandingCHIP = 0;
outstandingYieldToken = 0;
totalPoolUSDTCollateral = 0;
uint residualValue = ERC20_USDT(USDTContract).balanceOf(address(this));
ERC20_USDT(USDTContract).transfer(_tokenOwner, residualValue);
totalPoolBXTB = 0;
shareOfBxtb = ERC20Interface(BXTBContract).balanceOf(address(this));
ERC20Interface(BXTBContract).transfer(bxtbFoundation, shareOfBxtb);
collateralizationRatio = 100;
}
}
else revert("Unknown stake/redeem token");
}
| 8,490,690
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./events.sol";
import "../../../../infiniteProxy/IProxy.sol";
contract RebalancerModule is Events {
using SafeERC20 for IERC20;
/**
* @dev Only rebalancer gaurd.
*/
modifier onlyRebalancer() {
require(
_isRebalancer[msg.sender] ||
IProxy(address(this)).getAdmin() == msg.sender,
"only rebalancer"
);
_;
}
/**
* @dev low gas function just to collect profit.
* @notice Collected the profit & leave it in the DSA itself to optimize further on gas.
*/
function collectProfit(
bool isWeth, // either weth or steth
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
uint256 profits_ = getNewProfits();
require(amt_ <= profits_, "amount-exceeds-profit");
uint256 length_ = 1;
if (withdrawAmt_ > 0) length_++;
string[] memory targets_ = new string[](length_);
bytes[] memory calldata_ = new bytes[](length_);
address sellToken_ = isWeth
? address(wethContract)
: address(stethContract);
uint256 maxAmt_ = (getStethCollateralAmount() * _idealExcessAmt) /
10000;
if (withdrawAmt_ > 0) {
if (isWeth) {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
withdrawAmt_,
2,
0,
0
);
} else {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
withdrawAmt_,
0,
0
);
}
}
targets_[length_ - 1] = "1INCH-A";
calldata_[length_ - 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
_token,
sellToken_,
amt_,
unitAmt_,
oneInchData_,
0
);
_vaultDsa.cast(targets_, calldata_, address(this));
if (withdrawAmt_ > 0)
require(
IERC20(sellToken_).balanceOf(address(_vaultDsa)) <= maxAmt_,
"withdrawal-exceeds-max-limit"
);
emit collectProfitLog(isWeth, withdrawAmt_, amt_, unitAmt_);
}
struct RebalanceOneVariables {
bool isOk;
uint256 i;
uint256 j;
uint256 length;
string[] targets;
bytes[] calldatas;
bool criticalIsOk;
bool minIsOk;
}
/**
* @dev Rebalancer function to leverage and rebalance the position.
*/
function rebalanceOne(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] memory vaults_, // leverage using other vaults
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_, // 1inch's swap amount
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
if (leverageAmt_ < 1e14) leverageAmt_ = 0;
if (tokenWithdrawAmt_ < _tokenMinLimit) tokenWithdrawAmt_ = 0;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
RebalanceOneVariables memory v_;
v_.isOk = validateLeverageAmt(vaults_, amts_, leverageAmt_, swapAmt_);
require(v_.isOk, "swap-amounts-are-not-proper");
v_.length = amts_.length;
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) v_.j += 1;
if (leverageAmt_ > 0) v_.j += 1;
if (flashAmt_ > 0) v_.j += 3;
if (swapAmt_ > 0) v_.j += 2; // only deposit stEth in Aave if swap amt > 0.
if (v_.length > 0) v_.j += v_.length;
if (tokenWithdrawAmt_ > 0) v_.j += 2;
v_.targets = new string[](v_.j);
v_.calldatas = new bytes[](v_.j);
if (tokenDsaBal_ >= _tokenMinLimit) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
v_.i++;
}
if (leverageAmt_ > 0) {
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i++;
}
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
leverageAmt_,
2,
0,
0
);
v_.i++;
// Doing swaps from different vaults using deleverage to reduce other vaults riskiness if needed.
// It takes WETH from vault and gives astETH at 1:1
for (uint256 k = 0; k < v_.length; k++) {
v_.targets[v_.i] = "LITE-A"; // Instadapp Lite vaults connector
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deleverage(address,uint256,uint256,uint256)",
vaults_[k],
amts_[k],
0,
0
);
v_.i++;
}
if (swapAmt_ > 0) {
require(unitAmt_ > (1e18 - 10), "invalid-unit-amt");
v_.targets[v_.i] = "1INCH-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(stethContract),
address(wethContract),
swapAmt_,
unitAmt_,
oneInchData_,
0
);
v_.targets[v_.i + 1] = "AAVE-V2-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(stethContract),
type(uint256).max,
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.targets[v_.i + 1] = "INSTAPOOL-C";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i += 2;
}
}
if (tokenWithdrawAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
_token,
tokenWithdrawAmt_,
0,
0
);
v_.targets[v_.i + 1] = "BASIC-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"withdraw(address,uint256,address,uint256,uint256)",
_token,
tokenWithdrawAmt_,
address(this),
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(
v_.targets,
v_.calldatas
);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (v_.j > 0)
_vaultDsa.cast(v_.targets, v_.calldatas, address(this));
}
if (leverageAmt_ > 0)
require(
getWethBorrowRate() < _ratios.maxBorrowRate,
"high-borrow-rate"
);
(v_.criticalIsOk, , v_.minIsOk, ) = validateFinalPosition();
// this will allow auth to take position to max safe limit. Only have to execute when there's a need to make other vaults safer.
if (IProxy(address(this)).getAdmin() == msg.sender) {
if (leverageAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
} else {
if (leverageAmt_ > 0)
require(v_.minIsOk, "position risky after leverage");
if (tokenWithdrawAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
}
emit rebalanceOneLog(
flashTkn_,
flashAmt_,
route_,
vaults_,
amts_,
leverageAmt_,
swapAmt_,
tokenSupplyAmt_,
tokenWithdrawAmt_,
unitAmt_
);
}
/**
* @dev Rebalancer function for saving. To be run in times of making position less risky or to fill up the withdraw amount for users to exit
*/
function rebalanceTwo(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 tokenSupplyAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
require(unitAmt_ > (1e18 - _saveSlippage), "excess-slippage"); // TODO: set variable to update slippage? Here's it's 0.1% slippage.
uint256 i;
uint256 j;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) j += 1;
if (saveAmt_ > 0) j += 3;
if (flashAmt_ > 0) j += 3;
string[] memory targets_ = new string[](j);
bytes[] memory calldata_ = new bytes[](j);
if (tokenDsaBal_ >= _tokenMinLimit) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
i++;
}
if (saveAmt_ > 0) {
if (flashAmt_ > 0) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
i++;
}
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
saveAmt_,
0,
0
);
targets_[i + 1] = "1INCH-A";
calldata_[i + 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(wethContract),
address(stethContract),
saveAmt_,
unitAmt_,
oneInchData_,
1 // setId 1
);
targets_[i + 2] = "AAVE-V2-A";
calldata_[i + 2] = abi.encodeWithSignature(
"payback(address,uint256,uint256,uint256,uint256)",
address(wethContract),
0,
2,
1, // getId 1 to get the payback amount
0
);
if (flashAmt_ > 0) {
targets_[i + 3] = "AAVE-V2-A";
calldata_[i + 3] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
targets_[i + 4] = "INSTAPOOL-C";
calldata_[i + 4] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
}
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(targets_, calldata_);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (j > 0) _vaultDsa.cast(targets_, calldata_, address(this));
}
(, bool isOk_, , ) = validateFinalPosition();
require(isOk_, "position-risky");
emit rebalanceTwoLog(flashTkn_, flashAmt_, route_, saveAmt_, unitAmt_);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "../common/helpers.sol";
contract Events is Helpers {
event collectProfitLog(
bool isWeth,
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_
);
event rebalanceOneLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] vaults_,
uint256[] amts_,
uint256 leverageAmt_,
uint256 swapAmt_,
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_
);
event rebalanceTwoLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 unitAmt_
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProxy {
function getAdmin() external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./variables.sol";
contract Helpers is Variables {
/**
* @dev reentrancy gaurd.
*/
modifier nonReentrant() {
require(_status != 2, "ReentrancyGuard: reentrant call");
_status = 2;
_;
_status = 1;
}
/**
* @dev Helper function to get current eth borrow rate on aave.
*/
function getWethBorrowRate()
internal
view
returns (uint256 wethBorrowRate_)
{
(, , , , wethBorrowRate_, , , , , ) = aaveProtocolDataProvider
.getReserveData(address(wethContract));
}
/**
* @dev Helper function to get current token collateral on aave.
*/
function getTokenCollateralAmount()
internal
view
returns (uint256 tokenAmount_)
{
tokenAmount_ = _atoken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current steth collateral on aave.
*/
function getStethCollateralAmount()
internal
view
returns (uint256 stEthAmount_)
{
stEthAmount_ = astethToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current eth debt on aave.
*/
function getWethDebtAmount()
internal
view
returns (uint256 wethDebtAmount_)
{
wethDebtAmount_ = awethVariableDebtToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to token balances of everywhere.
*/
function getVaultBalances()
public
view
returns (
uint256 tokenCollateralAmt_,
uint256 stethCollateralAmt_,
uint256 wethDebtAmt_,
uint256 tokenVaultBal_,
uint256 tokenDSABal_,
uint256 netTokenBal_
)
{
tokenCollateralAmt_ = getTokenCollateralAmount();
stethCollateralAmt_ = getStethCollateralAmount();
wethDebtAmt_ = getWethDebtAmount();
tokenVaultBal_ = _token.balanceOf(address(this));
tokenDSABal_ = _token.balanceOf(address(_vaultDsa));
netTokenBal_ = tokenCollateralAmt_ + tokenVaultBal_ + tokenDSABal_;
}
// returns net eth. net stETH + ETH - net ETH debt.
function getNewProfits() public view returns (uint256 profits_) {
uint256 stEthCol_ = getStethCollateralAmount();
uint256 stEthDsaBal_ = stethContract.balanceOf(address(_vaultDsa));
uint256 wethDsaBal_ = wethContract.balanceOf(address(_vaultDsa));
uint256 positiveEth_ = stEthCol_ + stEthDsaBal_ + wethDsaBal_;
uint256 negativeEth_ = getWethDebtAmount() + _revenueEth;
profits_ = negativeEth_ < positiveEth_
? positiveEth_ - negativeEth_
: 0;
}
/**
* @dev Helper function to get current exchange price and new revenue generated.
*/
function getCurrentExchangePrice()
public
view
returns (uint256 exchangePrice_, uint256 newTokenRevenue_)
{
// net token balance is total balance. stETH collateral & ETH debt cancels out each other.
(, , , , , uint256 netTokenBalance_) = getVaultBalances();
netTokenBalance_ -= _revenue;
uint256 totalSupply_ = totalSupply();
uint256 exchangePriceWithRevenue_;
if (totalSupply_ != 0) {
exchangePriceWithRevenue_ =
(netTokenBalance_ * 1e18) /
totalSupply_;
} else {
exchangePriceWithRevenue_ = 1e18;
}
// Only calculate revenue if there's a profit
if (exchangePriceWithRevenue_ > _lastRevenueExchangePrice) {
uint256 newProfit_ = netTokenBalance_ -
((_lastRevenueExchangePrice * totalSupply_) / 1e18);
newTokenRevenue_ = (newProfit_ * _revenueFee) / 10000;
exchangePrice_ =
((netTokenBalance_ - newTokenRevenue_) * 1e18) /
totalSupply_;
} else {
exchangePrice_ = exchangePriceWithRevenue_;
}
}
struct ValidateFinalPosition {
uint256 tokenPriceInBaseCurrency;
uint256 ethPriceInBaseCurrency;
uint256 excessDebtInBaseCurrency;
uint256 netTokenColInBaseCurrency;
uint256 netTokenSupplyInBaseCurrency;
uint256 ratioMax;
uint256 ratioMin;
}
/**
* @dev Helper function to validate the safety of aave position after rebalancing.
*/
function validateFinalPosition()
internal
view
returns (
bool criticalIsOk_,
bool criticalGapIsOk_,
bool minIsOk_,
bool minGapIsOk_
)
{
(
uint256 tokenColAmt_,
uint256 stethColAmt_,
uint256 wethDebt_,
,
,
uint256 netTokenBal_
) = getVaultBalances();
uint256 ethCoveringDebt_ = (stethColAmt_ * _ratios.stEthLimit) / 10000;
uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_
? wethDebt_ - ethCoveringDebt_
: 0;
if (excessDebt_ > 0) {
IAavePriceOracle aaveOracle_ = IAavePriceOracle(
aaveAddressProvider.getPriceOracle()
);
ValidateFinalPosition memory validateFinalPosition_;
validateFinalPosition_.tokenPriceInBaseCurrency = aaveOracle_
.getAssetPrice(address(_token));
validateFinalPosition_.ethPriceInBaseCurrency = aaveOracle_
.getAssetPrice(address(wethContract));
validateFinalPosition_.excessDebtInBaseCurrency =
(excessDebt_ * validateFinalPosition_.ethPriceInBaseCurrency) /
1e18;
validateFinalPosition_.netTokenColInBaseCurrency =
(tokenColAmt_ *
validateFinalPosition_.tokenPriceInBaseCurrency) /
(10**_tokenDecimals);
validateFinalPosition_.netTokenSupplyInBaseCurrency =
(netTokenBal_ *
validateFinalPosition_.tokenPriceInBaseCurrency) /
(10**_tokenDecimals);
validateFinalPosition_.ratioMax =
(validateFinalPosition_.excessDebtInBaseCurrency * 10000) /
validateFinalPosition_.netTokenColInBaseCurrency;
validateFinalPosition_.ratioMin =
(validateFinalPosition_.excessDebtInBaseCurrency * 10000) /
validateFinalPosition_.netTokenSupplyInBaseCurrency;
criticalIsOk_ = validateFinalPosition_.ratioMax < _ratios.maxLimit;
criticalGapIsOk_ =
validateFinalPosition_.ratioMax > _ratios.maxLimitGap;
minIsOk_ = validateFinalPosition_.ratioMin < _ratios.minLimit;
minGapIsOk_ = validateFinalPosition_.ratioMin > _ratios.minLimitGap;
} else {
criticalIsOk_ = true;
minIsOk_ = true;
}
}
/**
* @dev Helper function to validate if the leverage amount is divided correctly amount other-vault-swaps and 1inch-swap .
*/
function validateLeverageAmt(
address[] memory vaults_,
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_
) internal pure returns (bool isOk_) {
uint256 l_ = vaults_.length;
isOk_ = l_ == amts_.length;
if (isOk_) {
uint256 totalAmt_ = swapAmt_;
for (uint256 i = 0; i < l_; i++) {
totalAmt_ = totalAmt_ + amts_[i];
}
isOk_ = totalAmt_ <= leverageAmt_; // total amount should not be more than leverage amount
isOk_ = isOk_ && ((leverageAmt_ * 9999) / 10000) < totalAmt_; // total amount should be more than (0.9999 * leverage amount). 0.01% slippage gap.
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
contract ConstantVariables is ERC20Upgradeable {
IInstaIndex internal constant instaIndex =
IInstaIndex(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
IERC20 internal constant wethContract = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 internal constant stethContract = IERC20(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IAaveProtocolDataProvider internal constant aaveProtocolDataProvider =
IAaveProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveAddressProvider internal constant aaveAddressProvider =
IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
IERC20 internal constant awethVariableDebtToken =
IERC20(0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf);
IERC20 internal constant astethToken =
IERC20(0x1982b2F5814301d4e9a8b0201555376e62F82428);
IInstaList internal constant instaList =
IInstaList(0x4c8a1BEb8a87765788946D6B19C6C6355194AbEb);
}
contract Variables is ConstantVariables {
uint256 internal _status = 1;
// only authorized addresses can rebalance
mapping(address => bool) internal _isRebalancer;
IERC20 internal _token;
uint8 internal _tokenDecimals;
uint256 internal _tokenMinLimit;
IERC20 internal _atoken;
IDSA internal _vaultDsa;
struct Ratios {
uint16 maxLimit; // Above this withdrawals are not allowed
uint16 maxLimitGap;
uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap
uint16 minLimitGap;
uint16 stEthLimit; // if 7500. Meaning stETH collateral covers 75% of the ETH debt. Excess ETH will be covered by token limit.
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
}
Ratios internal _ratios;
// last revenue exchange price (helps in calculating revenue)
// Exchange price when revenue got updated last. It'll only increase overtime.
uint256 internal _lastRevenueExchangePrice;
uint256 internal _revenueFee; // 1000 = 10% (10% of user's profit)
uint256 internal _revenue;
uint256 internal _revenueEth;
uint256 internal _withdrawalFee; // 10000 = 100%
uint256 internal _idealExcessAmt; // 10 means 0.1% of total stEth/Eth supply (collateral + ideal balance)
uint256 internal _swapFee; // 5 means 0.05%. This is the fee on leverage function which allows swap of stETH -> ETH
uint256 internal _saveSlippage; // 1e16 means 1%
uint256 internal _deleverageFee; // 1 means 0.01%
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IInstaIndex {
function build(
address owner_,
uint256 accountVersion_,
address origin_
) external returns (address account_);
}
interface IDSA {
function cast(
string[] calldata _targetNames,
bytes[] calldata _datas,
address _origin
) external payable returns (bytes32);
}
interface IAaveProtocolDataProvider {
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface IAaveAddressProvider {
function getPriceOracle() external view returns (address);
}
interface IAavePriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IInstaList {
function accountID(address) external view returns (uint64);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
Helper function to get current steth collateral on aave./
|
function getStethCollateralAmount()
internal
view
returns (uint256 stEthAmount_)
{
stEthAmount_ = astethToken.balanceOf(address(_vaultDsa));
}
| 161,548
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
//import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./BaseERC1155.sol";
import "./TendiesCard.sol";
/**
* @title TendiesBox
* TendiesBox - a contract for semi-fungible tokens
*/
contract TendiesBox is BaseERC1155
{
using SafeMath for uint256;
// Must be sorted by rarity
struct BoxConfig {
uint16 maxQuantityPerOpen;
uint16[] classProbabilities; // Out of the basis points, in descending order
uint16[] classIds;
uint16[] guaranteedClassIds;
}
mapping (uint256 => BoxConfig) public boxConfigs;
// Information for random card pack pulls
uint256 seed;
uint256 constant INVERSE_BASIS_POINT = 10000;
// NFT Contract
TendiesCard public nftContract;
constructor(
string memory _uri,
address _nftAddress,
address _proxyRegistryAddress
)
BaseERC1155(
"Tendies Box",
"TENDBOX",
_uri,
_proxyRegistryAddress
)
public
{
nftContract = TendiesCard(_nftAddress);
}
/**
* Only Token Creator Functions
**/
function create(
uint16 _maxQuantityPerOpen,
uint16[] memory _classIds,
uint16[] memory _classProbabilities,
uint16[] memory _guaranteedClassIds
)
external
{
require(hasRole(CREATOR_ROLE, _msgSender()), "Not a creator");
require(_maxQuantityPerOpen > 0, "Packs must produce at least one card");
require(_guaranteedClassIds.length <= _maxQuantityPerOpen, "Too many guaranteed classes");
for (uint256 guarIdx = 0; guarIdx < _guaranteedClassIds.length; guarIdx++) {
bool found = false;
for (uint256 classIdx = 0; classIdx < _classIds.length; classIdx++) {
if (_guaranteedClassIds[guarIdx] == _classIds[classIdx]) {
found = true;
break;
}
}
require(found, "Invalid guaranteed class ID");
}
// Keep track of the latest ID
maxTokenID = maxTokenID.add(1);
// Add the pack config
boxConfigs[maxTokenID] = BoxConfig({
maxQuantityPerOpen: _maxQuantityPerOpen,
classProbabilities: _classProbabilities,
classIds: _classIds,
guaranteedClassIds: _guaranteedClassIds
});
}
// Open a pack
function open(
uint256 _boxId,
uint256 _amount
)
external
{
// Open on behalf of ourself
openFor(_boxId, _amount, _msgSender());
}
// Open a pack
function openFor(
uint256 _boxId,
uint256 _amount,
address _recipient
)
public
{
// Operator check occurs here
require(
_recipient == _msgSender() || isApprovedForAll(_recipient, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
// Burn the boxes, decrease total supply
_burn(_recipient, _boxId, _amount);
totalSupply[_boxId] = totalSupply[_boxId].sub(_amount);
// If we make it here, we're minting tendies
// Load settings for this box option
BoxConfig memory settings = boxConfigs[_boxId];
// Iterate over the quantity of boxes specified
for (uint256 boxIdx = 0; boxIdx < _amount; boxIdx++) {
uint256 arrIndex = 0;
uint256[] memory tokenIdsToMint = new uint256[](settings.maxQuantityPerOpen);
uint256[] memory quantitiesToMint = new uint256[](settings.maxQuantityPerOpen);
// Process guaranteed token ids
for (uint256 classIdx = 0; classIdx < settings.guaranteedClassIds.length; classIdx++) {
uint256 classId = settings.guaranteedClassIds[classIdx];
// Don't try to access elements that don't exist
if (arrIndex < settings.maxQuantityPerOpen) {
tokenIdsToMint[arrIndex] = _pickRandomAvailableTokenIdForClass(classId);
quantitiesToMint[arrIndex] = 1;
arrIndex++;
}
}
// Process non-guaranteed ids
while (arrIndex < settings.maxQuantityPerOpen) {
// Keep track of token IDs we're minting and their quantities
uint256 class = _pickRandomClass(settings.classProbabilities, settings.classIds);
tokenIdsToMint[arrIndex] = _pickRandomAvailableTokenIdForClass(class);
quantitiesToMint[arrIndex] = 1;
arrIndex++;
}
// Mint all of the tokens
nftContract.mintBatch(_recipient, tokenIdsToMint, quantitiesToMint, "");
}
}
/////
// HELPER FUNCTIONS
/////
function _pickRandomClass(
uint16[] memory _classProbabilities,
uint16[] memory _classIds
)
internal
returns (uint256)
{
uint16 value = uint16(_random().mod(INVERSE_BASIS_POINT));
// Start at top class (length - 1)
// skip common (0), we default to it
for (uint256 idx = _classProbabilities.length - 1; idx > 0; idx--) {
uint16 probability = _classProbabilities[idx];
if (value < probability) {
return _classIds[idx];
} else {
value = value - probability;
}
}
return _classIds[0];
}
function _pickRandomAvailableTokenIdForClass(
uint256 _classId
)
internal
returns (uint256)
{
uint256 classTokenCount = nftContract.classTokenCounts(_classId);
if (classTokenCount == 0) {
return 0;
}
uint256 randIndex = _random().mod(classTokenCount);
return nftContract.classToTokenIds(_classId, randIndex);
}
function _random()
internal
returns (uint256)
{
uint256 randomNumber = uint256(
keccak256(
abi.encodePacked(
blockhash(block.number - 1),
msg.sender,
seed
)
)
);
seed = randomNumber;
return randomNumber;
}
function setSeed(
uint256 _newSeed
)
public
onlyOwner
{
seed = _newSeed;
}
}
|
Open a pack Open on behalf of ourself
|
function open(
uint256 _boxId,
uint256 _amount
)
external
{
openFor(_boxId, _amount, _msgSender());
}
| 5,521,033
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;
import {
IERC165,
ERC721,
IERC721,
IERC721Receiver,
Strings
} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import {Settings} from "./Settings.sol";
contract Flashmint is
ERC721,
IERC721Receiver,
ReentrancyGuard,
IERC2981
{
using Strings for uint256;
/// -------------------------
/// === TOKEN INFORMATION ===
/// -------------------------
/// @notice the ERC721 token address of this vault's token
address public token;
/// @notice the erc721 token ID of this vault's token
uint256 public id;
/// -------------------------
/// === VAULT INFORMATION ===
/// -------------------------
/// @notice the protocol-wide settings
address public immutable settings;
/// @notice the price a lender must pay to mint with this token. in wei, ie 18 decimals (10**18 = 1)
uint256 public fee;
// NOT_ACTIVE when created, ACTIVE when initialized & ready for use
// FINISHED when NFT is withdrawn by owner
enum State { NOT_ACTIVE, ACTIVE, FINISHED }
State public vaultState;
/// @notice owner may reserve certain mints for themselves
mapping (address => bool) public reserved;
/// @notice NFTs owed to borrowers
/// @dev this only applies for NFTs minted without safeMint
/// note that tokenIds aren't reserved 1:1
/// token -> borrower -> number of NFTs
mapping (address => mapping (address => uint256)) public claimable;
/// @notice total number of NFTs owed to borrowers
/// the rest are prob airdrops and can be claimed by vault owner
/// token -> number of NFTs
mapping (address => uint256) public totalClaimable;
/// -------------------------
/// === MINT INFORMATION ===
/// -------------------------
enum FlightStatus {
READY, // before call to external NFT
INFLIGHT, // during call to external NFT
LANDED // once NFT is received in `onERC721Received`
}
struct MintRequest {
FlightStatus flightStatus;
address expectedNFTContractAddress;
uint256[] newids; // @notice this is only defined if flightStatus != READY
}
/// @notice state variable is needed to track a mint request because
/// we're reliant on the ERC721Receiver callback to get id
MintRequest private safeMintReq;
/// -------------------------
/// ======== EVENTS ========
/// -------------------------
/// @notice Emitted when `minter` borrows this NFT to mint `minted`
event FlashmintedSafe(address indexed minter, address indexed minted, uint256[] tokenIds, uint256 fee);
/// @notice Emitted when `minter` mints `amount` of NFTs (minted)
event Flashminted(address indexed minter, address indexed minted, uint256 amount, uint256 fee);
/// @notice Emitted when someone claims an NFT minted with unsafely
event ClaimedMint(address indexed claimant, address indexed minted, uint256 tokenId);
/// @notice Emitted when initial depositor reclaims their NFT and ends this contract.
event Closed(address depositor);
/// @notice Emitted when the claimer cashes out their fees
event Cash(address depositor, uint256 amount);
/// @notice Emitted when the cost is updated
event FeeUpdated(uint256 amount);
/// @notice Emitted when the owner reserves a mint for themselves
event Reserved(address indexed nft, bool indexed reserved);
string constant _name = unicode"⚡Flashmint Held NFT";
string constant _symbol = unicode"⚡FLASH";
constructor(address _settings) ERC721(_name, _symbol) {
vaultState = State.NOT_ACTIVE;
settings = _settings;
}
function name() public view override returns (string memory){return _name;}
function symbol() public view override returns (string memory){return _symbol;}
/// ---------------------------
/// === MODIFIERS ===
/// ---------------------------
// @dev access control for vault admin functions
modifier onlyVaultOwner {
require(msg.sender == ownerOf(0), "not owner");
_;
}
// @dev for use with calls to external contracts
modifier noStealing {
_;
require(IERC721(token).ownerOf(id) == address(this), "no stealing");
}
// @dev prevent malicious calls to `token` that eg approve() others
modifier notToken(address _token) {
require(token != _token, "can't call underlying");
_;
}
modifier noMeanCalldata(bytes calldata _mintData) {
bytes4 APPROVE = bytes4(0x095ea7b3);
bytes4 APPROVE_FOR_ALL = bytes4(0xa22cb465);
bytes4 sig = bytes4(_mintData[:4]);
require(
sig != APPROVE && sig != APPROVE_FOR_ALL,
"no mean sigs"
);
_;
}
/// ---------------------------
/// === LIFECYCLE FUNCTIONS ===
/// ---------------------------
function initializeWithNFT(address _token, uint256 _id, address _depositor, uint256 _fee) external nonReentrant {
require(vaultState == State.NOT_ACTIVE, "already active");
require(_token != _depositor, "self deposit");
token = _token;
id = _id;
vaultState = State.ACTIVE;
fee = _fee;
_safeMint(_depositor, 0);
emit FeeUpdated(_fee);
}
/// @notice allow the depositor to reclaim their NFT, ending this flashmint
function withdrawNFT() external nonReentrant {
vaultState = State.FINISHED;
// pay out remaining balance
_withdrawEth();
address recipient = ownerOf(0);
// @note requires that msgSender controls id 0 of this vault
transferFrom(recipient, address(this), 0);
// Burn LP token
_burn(0);
// Distribute underlying token
IERC721(token).safeTransferFrom(address(this), recipient, id);
emit Closed(msg.sender);
}
/// @notice allows anyone to forward payments to the depositor
function withdrawEth() external nonReentrant {
require(vaultState != State.NOT_ACTIVE, "State is NOT_ACTIVE");
_withdrawEth();
}
function _withdrawEth() internal {
address recipient = ownerOf(0);
uint256 amount = address(this).balance;
uint256 protocolFee = amount * Settings(settings).protocolFeeBips() / 10000;
address protocol = Settings(settings).protocolFeeReceiver();
bool sent;
if (protocolFee > 0 && protocol != address(0)) {
(sent, ) = payable(protocol).call{value: protocolFee}("");
require(sent, "_withdrawEth: protocol payment failed");
}
(sent, ) = payable(recipient).call{value: amount - protocolFee}("");
require(sent, "_withdrawEth: payment failed");
emit Cash(recipient, amount);
}
/// ---------------------------
/// === OWNER MGMT UTILITIES ===
/// ---------------------------
/// @notice allow the depositor to update their fee
function updateFee(uint256 _fee) external
onlyVaultOwner
nonReentrant
{
fee = _fee;
emit FeeUpdated(_fee);
}
/// @notice allow the depositor to reserve a mint for themselves
function reserve(address _token, bool _reserved) external
onlyVaultOwner
{
reserved[_token] = _reserved;
emit Reserved(_token, _reserved);
}
/// @notice let vault owner rescue eg airdrops
function rescueCoin(address _coin) external
onlyVaultOwner
notToken(_coin)
noStealing
{
uint256 balance = IERC20(_coin).balanceOf(address(this));
IERC20(_coin).transfer(msg.sender, balance);
}
/// @notice let vault owner rescue eg airdrops
function rescueNFT(address _token, uint256 _tokenId) external
nonReentrant
onlyVaultOwner
notToken(_token)
noStealing
{
// ensure token doesn't belong to a customer
require(
IERC721(_token).balanceOf(address(this)) >
totalClaimable[_token],
"spoken for"
);
IERC721(_token).transferFrom(address(this), msg.sender, _tokenId);
}
/// ---------------------------
/// === FLASHMINT FUNCTIONS ===
/// ---------------------------
/// @notice mint a derivative NFT and send it to the caller
/// @notice derivative must use `_safeMint` because need onERC721Received callback
/// @param _derivativeNFT the NFT user would like to mint
/// @param _mintData data for the mint function ie abi.encodeWithSignature(...)
function lendToMintSafe (
address _derivativeNFT,
bytes calldata _mintData
) external payable
nonReentrant
notToken(_derivativeNFT)
noMeanCalldata(_mintData)
noStealing
{
require(vaultState == State.ACTIVE, "vault not active");
require(msg.value >= fee, "didn't send enough eth");
require(!reserved[_derivativeNFT] || msg.sender == ownerOf(0), "NFT is reserved");
require(_derivativeNFT != address(this), "must call another contract");
require(_derivativeNFT != ownerOf(0), "must call another contract");
// request data is updated by nested functions, ie onERC721Received
delete safeMintReq.newids;
safeMintReq = MintRequest({
flightStatus: FlightStatus.INFLIGHT,
expectedNFTContractAddress: _derivativeNFT,
newids: new uint256[](0) // not used unless FlightStatus is LANDED
});
// mint the derivative and make sure we got it
(bool success, ) = _derivativeNFT.call{value: msg.value - fee}(_mintData);
require(success, "call to mint failed");
require(safeMintReq.flightStatus == FlightStatus.LANDED, "didnt mint");
uint256 len = safeMintReq.newids.length;
for (uint256 i = 0; i < len; i++) {
// @note: asserts that we own the token
IERC721(_derivativeNFT).safeTransferFrom(address(this), msg.sender, safeMintReq.newids[i]);
}
emit FlashmintedSafe(msg.sender, _derivativeNFT, safeMintReq.newids, fee);
// reset state variable for next calls.
delete safeMintReq.newids;
delete safeMintReq;
safeMintReq = MintRequest({
flightStatus: FlightStatus.READY,
expectedNFTContractAddress: address(0),
newids: new uint256[](0)
});
}
function onERC721Received(
address,
address,
uint256 _id,
bytes calldata
) external virtual override returns (bytes4) {
if (safeMintReq.flightStatus == FlightStatus.INFLIGHT
&& msg.sender == safeMintReq.expectedNFTContractAddress
){
// we're receiving the expected derivative
safeMintReq.flightStatus = FlightStatus.LANDED;
safeMintReq.newids.push(_id);
}
// Note: can still receive other NFTs
return this.onERC721Received.selector;
}
/// @notice mint an NFT that doesn't use `safeMint()`
/// without knowing the tokenId, two txs are required.
/// @notice this function is unsafe if _derivativeNFT is sketchy,
/// ie has non ERC721 `approve` fns,
/// @dev see `lendToMintSafe` for _safeMint() NFTs
function lendToMint(
address _derivativeNFT,
bytes calldata _mintData
) external payable
nonReentrant
notToken(_derivativeNFT)
noMeanCalldata(_mintData)
noStealing
{
require(vaultState == State.ACTIVE, "vault not active");
require(msg.value >= fee, "didn't send enough eth");
require(!reserved[_derivativeNFT] || msg.sender == ownerOf(0), "NFT is reserved");
require(_derivativeNFT != address(this), "must call another contract");
require(_derivativeNFT != ownerOf(0), "must call another contract");
uint256 balanceBefore = IERC721(_derivativeNFT).balanceOf(address(this));
// mint the derivative and make sure we got it
(bool success, ) = _derivativeNFT.call{value: msg.value - fee}(_mintData);
require(success, "call to mint failed");
// check that we minted successfully
uint256 gained = IERC721(_derivativeNFT).balanceOf(address(this)) - balanceBefore;
require(gained > 0, "didnt mint");
// set them aside for the minter
claimable[_derivativeNFT][msg.sender] += gained;
totalClaimable[_derivativeNFT] += gained;
emit Flashminted(msg.sender, _derivativeNFT, gained, fee);
}
function claimMintedNFT(address _derivativeNFT, uint256 _newTokenId) external
notToken(_derivativeNFT)
noStealing
{
// throws if msg.sender doesn't have a claimable token
claimable[_derivativeNFT][msg.sender] --;
totalClaimable[_derivativeNFT] --;
// throws if we don't own `_newTokenId`
IERC721(_derivativeNFT).safeTransferFrom(address(this), msg.sender, _newTokenId);
emit ClaimedMint(msg.sender, _derivativeNFT, _newTokenId);
}
/// ---------------------------
/// === TOKENURI FUNCTIONS ===
/// ---------------------------
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(vaultState == State.ACTIVE, "no token");
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory tAddr = toAsciiString(token);
string memory tId = id.toString();
string memory myAddr = toAsciiString(address(this));
return string(abi.encodePacked(
Settings(settings).baseURI(),
myAddr,
"/",
tokenId.toString(),
"/",
tAddr,
"/",
tId,
"/"
));
}
function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
/// ---------------------------
/// = PROJECT SETTINGS & MARKETPLACES =
/// ---------------------------
// some NFT marketplaces wants an `owner()` function
function owner() public view virtual returns (address) {
return Settings(settings).marketplaceAdmin();
}
// eventual compatibility with royalties
function royaltyInfo(uint256 /*tokenId*/, uint256 _salePrice)
external view virtual override
returns (address receiver, uint256 royaltyAmount) {
receiver = Settings(settings).royaltyReceiver();
royaltyAmount = _salePrice * Settings(settings).royaltyPercentBips() / 10000;
}
function supportsInterface(bytes4 interfaceId)
public view virtual
override(IERC165, ERC721)
returns (bool)
{
return interfaceId == type(IERC2981).interfaceId
|| super.supportsInterface(interfaceId);
}
receive() external payable{}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract Settings is Ownable {
event RoyaltyInfoUpdated(address indexed receiver, uint256 royaltyPercentBips);
event ProtocolFeeUpdated(address indexed receiver, uint256 protocolFeeBips);
event MarketplaceAdminUpdated(address indexed marketplaceAdmin);
// royalties on LP tokens
uint256 public royaltyPercentBips; // ie 250 = 2.5%
address public royaltyReceiver;
// protocol fee on flashmints
uint256 public protocolFeeBips;
address public protocolFeeReceiver;
// some NFT marketplaces want NFTs to have an `owner()` function
address public marketplaceAdmin;
string public baseURI;
// royalties, protocol fee are 0 unless turned on
constructor() {
baseURI = "http://flashmint.ooo/api/tokenURI/";
}
function setRoyaltyPercentBips(uint256 _royaltyPercentBips) external onlyOwner {
require(_royaltyPercentBips < 1000, "royalties: cmon"); // force prevent high royalties
royaltyPercentBips = _royaltyPercentBips;
emit RoyaltyInfoUpdated(royaltyReceiver, _royaltyPercentBips);
}
function setRoyaltyReceiver(address _royaltyReceiver) external onlyOwner {
royaltyReceiver = _royaltyReceiver;
emit RoyaltyInfoUpdated(_royaltyReceiver, royaltyPercentBips);
}
function setProtocolFee(uint256 _protocolFeeBips) external onlyOwner {
require(_protocolFeeBips < 5000, "fee: cmon");
protocolFeeBips = _protocolFeeBips;
emit ProtocolFeeUpdated(protocolFeeReceiver, _protocolFeeBips);
}
function setProtocolFeeReceiver(address _protocolFeeReceiver) external onlyOwner {
protocolFeeReceiver = _protocolFeeReceiver;
emit ProtocolFeeUpdated(_protocolFeeReceiver, protocolFeeBips);
}
function setMarketplaceAdmin(address _marketplaceAdmin) external onlyOwner {
marketplaceAdmin = _marketplaceAdmin;
emit MarketplaceAdminUpdated(_marketplaceAdmin);
}
function setBaseURI(string calldata _baseURI) external onlyOwner {
baseURI = _baseURI;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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);
}
}
|
--------------------------- === OWNER MGMT UTILITIES === --------------------------- allow the depositor to update their fee
|
function updateFee(uint256 _fee) external
onlyVaultOwner
nonReentrant
{
fee = _fee;
emit FeeUpdated(_fee);
}
| 14,948,758
|
./full_match/97/0xeB4BBc50CA990f3Cd1E3FbcAFFD1eCF59FB06682/sources/project_/contracts/crowdsale.sol
|
Change Wallet. newWallet Crowdsale wallet/
|
function _changeWallet(address newWallet) virtual internal {
wallet = newWallet;
}
| 3,261,635
|
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: contracts/governance/DelegateReference.sol
/**
* @title Delegate reference to be used in other contracts
*/
interface DelegateReference {
/**
* @notice Stake specified amount of tokens to the delegate to participate in coin distribution
*/
function stake(uint256 _amount) external;
/**
* @notice Unstake specified amount of tokens from the delegate
*/
function unstake(uint256 _amount) external;
/**
* @notice Return number of tokens staked by the specified staker
*/
function stakeOf(address _staker) external view returns (uint256);
/**
* @notice Sets Aerum address for delegate & calling staker
*/
function setAerumAddress(address _aerum) external;
}
// File: contracts/vesting/MultiVestingWallet.sol
/**
* @title TokenVesting
* @notice 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 MultiVestingWallet is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(address indexed account, uint256 amount);
event Revoked(address indexed account);
event UnRevoked(address indexed account);
event ReturnTokens(uint256 amount);
event Promise(address indexed account, uint256 amount);
event Stake(address indexed delegate, uint256 amount);
event Unstake(address indexed delegate, uint256 amount);
ERC20 public token;
uint256 public cliff;
uint256 public start;
uint256 public duration;
uint256 public staked;
bool public revocable;
address[] public accounts;
mapping(address => bool) public known;
mapping(address => uint256) public promised;
mapping(address => uint256) public released;
mapping(address => bool) public revoked;
/**
* @notice Creates a vesting contract that vests its balance of any ERC20 token to the
* of the balance will have vested.
* @param _token token being vested
* @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 _token,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_token != address(0));
require(_cliff <= _duration);
token = ERC20(_token);
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() external {
_release(msg.sender);
}
/**
* @notice Transfers vested tokens to list of beneficiary.
* @param _addresses List of beneficiaries
*/
function releaseBatch(address[] _addresses) external {
for (uint256 index = 0; index < _addresses.length; index++) {
_release(_addresses[index]);
}
}
/**
* @notice Transfers vested tokens to batch of beneficiaries (starting 0)
* @param _start Index of first beneficiary to release tokens
* @param _count Number of beneficiaries to release tokens
*/
function releaseBatchPaged(uint256 _start, uint256 _count) external {
uint256 last = _start.add(_count);
if (last > accounts.length) {
last = accounts.length;
}
for (uint256 index = _start; index < last; index++) {
_release(accounts[index]);
}
}
/**
* @notice Transfers vested tokens to all beneficiaries.
*/
function releaseAll() external {
for (uint256 index = 0; index < accounts.length; index++) {
_release(accounts[index]);
}
}
/**
* @notice Internal transfer of vested tokens to beneficiary.
*/
function _release(address _beneficiary) internal {
uint256 amount = releasableAmount(_beneficiary);
if (amount > 0) {
released[_beneficiary] = released[_beneficiary].add(amount);
token.safeTransfer(_beneficiary, amount);
emit Released(_beneficiary, amount);
}
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _beneficiary Account which will be revoked
*/
function revoke(address _beneficiary) public onlyOwner {
require(revocable);
require(!revoked[_beneficiary]);
promised[_beneficiary] = vestedAmount(_beneficiary);
revoked[_beneficiary] = true;
emit Revoked(_beneficiary);
}
/**
* @notice Allows the owner to revoke the vesting for few addresses.
* @param _addresses Accounts which will be unrevoked
*/
function revokeBatch(address[] _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
revoke(_addresses[index]);
}
}
/**
* @notice Allows the owner to unrevoke the vesting.
* @param _beneficiary Account which will be unrevoked
*/
function unRevoke(address _beneficiary) public onlyOwner {
require(revocable);
require(revoked[_beneficiary]);
revoked[_beneficiary] = false;
emit UnRevoked(_beneficiary);
}
/**
* @notice Allows the owner to unrevoke the vesting for few addresses.
* @param _addresses Accounts which will be unrevoked
*/
function unrevokeBatch(address[] _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
unRevoke(_addresses[index]);
}
}
/**
* @notice Calculates the amount that has already vested but hasn't been released yet.
* @param _beneficiary Account which gets vested tokens
*/
function releasableAmount(address _beneficiary) public view returns (uint256) {
return vestedAmount(_beneficiary).sub(released[_beneficiary]);
}
/**
* @notice Calculates the amount that has already vested.
* @param _beneficiary Account which gets vested tokens
*/
function vestedAmount(address _beneficiary) public view returns (uint256) {
uint256 totalPromised = promised[_beneficiary];
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_beneficiary]) {
return totalPromised;
} else {
return totalPromised.mul(block.timestamp.sub(start)).div(duration);
}
}
/**
* @notice Calculates the amount of free tokens in contract
*/
function remainingBalance() public view returns (uint256) {
uint256 tokenBalance = token.balanceOf(address(this));
uint256 totalPromised = 0;
uint256 totalReleased = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
totalPromised = totalPromised.add(promised[account]);
totalReleased = totalReleased.add(released[account]);
}
uint256 promisedNotReleased = totalPromised.sub(totalReleased);
if (promisedNotReleased > tokenBalance) {
return 0;
}
return tokenBalance.sub(promisedNotReleased);
}
/**
* @notice Calculates amount of tokens promised
*/
function totalPromised() public view returns (uint256) {
uint256 total = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
total = total.add(promised[account]);
}
return total;
}
/**
* @notice Calculates amount of tokens released
*/
function totalReleased() public view returns (uint256) {
uint256 total = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
total = total.add(released[account]);
}
return total;
}
/**
* @notice Returns free tokens to owner
*/
function returnRemaining() external onlyOwner {
uint256 remaining = remainingBalance();
require(remaining > 0);
token.safeTransfer(owner, remaining);
emit ReturnTokens(remaining);
}
/**
* @notice Returns all tokens to owner
*/
function returnAll() external onlyOwner {
uint256 remaining = token.balanceOf(address(this));
token.safeTransfer(owner, remaining);
emit ReturnTokens(remaining);
}
/**
* @notice Sets promise to account
* @param _beneficiary Account which gets vested tokens
* @param _amount Amount of tokens vested
*/
function promise(address _beneficiary, uint256 _amount) public onlyOwner {
if (!known[_beneficiary]) {
known[_beneficiary] = true;
accounts.push(_beneficiary);
}
promised[_beneficiary] = _amount;
emit Promise(_beneficiary, _amount);
}
/**
* @notice Sets promise to list of account
* @param _addresses Accounts which will get promises
* @param _amounts Promise amounts
*/
function promiseBatch(address[] _addresses, uint256[] _amounts) external onlyOwner {
require(_addresses.length == _amounts.length);
for (uint256 index = 0; index < _addresses.length; index++) {
promise(_addresses[index], _amounts[index]);
}
}
/**
* @notice Returns full list if beneficiaries
*/
function getBeneficiaries() external view returns (address[]) {
return accounts;
}
/**
* @notice Returns number of beneficiaries
*/
function getBeneficiariesCount() external view returns (uint256) {
return accounts.length;
}
/**
* @notice Stake specified amount of vested tokens to the delegate by the beneficiary
*/
function stake(address _delegate, uint256 _amount) external onlyOwner {
staked = staked.add(_amount);
token.approve(_delegate, _amount);
DelegateReference(_delegate).stake(_amount);
emit Stake(_delegate, _amount);
}
/**
* @notice Unstake the given number of vested tokens by the beneficiary
*/
function unstake(address _delegate, uint256 _amount) external onlyOwner {
staked = staked.sub(_amount);
DelegateReference(_delegate).unstake(_amount);
emit Unstake(_delegate, _amount);
}
}
// File: contracts\registry\ContractRegistry.sol
/**
* @title Contract registry
*/
contract ContractRegistry is Ownable {
struct ContractRecord {
address addr;
bytes32 name;
bool enabled;
}
address private token;
/**
* @dev contracts Mapping of contracts
*/
mapping(bytes32 => ContractRecord) private contracts;
/**
* @dev contracts Mapping of contract names
*/
bytes32[] private contractsName;
event ContractAdded(bytes32 indexed _name);
event ContractRemoved(bytes32 indexed _name);
constructor(address _token) public {
require(_token != address(0), "Token is required");
token = _token;
}
/**
* @dev Returns contract by name
* @param _name Contract's name
*/
function getContractByName(bytes32 _name) external view returns (address, bytes32, bool) {
ContractRecord memory record = contracts[_name];
if(record.addr == address(0) || !record.enabled) {
return;
}
return (record.addr, record.name, record.enabled);
}
/**
* @dev Returns contract's names
*/
function getContractNames() external view returns (bytes32[]) {
uint count = 0;
for(uint i = 0; i < contractsName.length; i++) {
if(contracts[contractsName[i]].enabled) {
count++;
}
}
bytes32[] memory result = new bytes32[](count);
uint j = 0;
for(i = 0; i < contractsName.length; i++) {
if(contracts[contractsName[i]].enabled) {
result[j] = contractsName[i];
j++;
}
}
return result;
}
/**
* @notice Creates a vesting contract that vests its balance of any ERC20 token to the
* of the balance will have vested.
* @param _name contract's name
* @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
*/
function addContract(
bytes32 _name,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable) external onlyOwner {
require(contracts[_name].addr == address(0), "Contract's name should be unique");
require(_cliff <= _duration, "Cliff shall be bigger than duration");
MultiVestingWallet wallet = new MultiVestingWallet(token, _start, _cliff, _duration, _revocable);
wallet.transferOwnership(msg.sender);
address walletAddr = address(wallet);
ContractRecord memory record = ContractRecord({
addr: walletAddr,
name: _name,
enabled: true
});
contracts[_name] = record;
contractsName.push(_name);
emit ContractAdded(_name);
}
/**
* @dev Enables/disables contract by address
* @param _name Name of the contract
*/
function setEnabled(bytes32 _name, bool enabled) external onlyOwner {
ContractRecord memory record = contracts[_name];
require(record.addr != address(0), "Contract with specified address does not exist");
contracts[_name].enabled = enabled;
}
/**
* @dev Set's new name
* @param _oldName Old name of the contract
* @param _newName New name of the contract
*/
function setNewName(bytes32 _oldName, bytes32 _newName) external onlyOwner {
require(contracts[_newName].addr == address(0), "Contract's name should be unique");
ContractRecord memory record = contracts[_oldName];
require(record.addr != address(0), "Contract's old name should be defined");
record.name = _newName;
contracts[_newName] = record;
contractsName.push(_newName);
delete contracts[_oldName];
contractsName = removeByValue(contractsName, _oldName);
}
function removeByValue(bytes32[] memory _array, bytes32 _name) private pure returns(bytes32[]) {
uint i = 0;
uint j = 0;
bytes32[] memory outArray = new bytes32[](_array.length - 1);
while (i < _array.length) {
if(_array[i] != _name) {
outArray[j] = _array[i];
j++;
}
i++;
}
return outArray;
}
}
|
Returns number of beneficiaries/
|
function getBeneficiariesCount() external view returns (uint256) {
return accounts.length;
}
| 7,222,058
|
pragma solidity 0.5.10;
pragma experimental ABIEncoderV2;
import 'ROOT/external/IExchange.sol';
import 'ROOT/libraries/ReentrancyGuard.sol';
import 'ROOT/external/IWallet.sol';
import 'ROOT/libraries/math/SafeMathUint256.sol';
import 'ROOT/libraries/token/IERC1155.sol';
contract ZeroXExchange is IExchange, ReentrancyGuard {
using SafeMathUint256 for uint256;
// EIP191 header for EIP712 prefix
string constant internal EIP191_HEADER = "\x19\x01";
// EIP712 Domain Name value
string constant internal EIP712_DOMAIN_NAME = "0x Protocol";
// EIP712 Domain Version value
string constant internal EIP712_DOMAIN_VERSION = "2";
// Hash of the EIP712 Domain Separator Schema
bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(
abi.encodePacked(
"Order(",
"address makerAddress,",
"address takerAddress,",
"address feeRecipientAddress,",
"address senderAddress,",
"uint256 makerAssetAmount,",
"uint256 takerAssetAmount,",
"uint256 makerFee,",
"uint256 takerFee,",
"uint256 expirationTimeSeconds,",
"uint256 salt,",
"bytes makerAssetData,",
"bytes takerAssetData",
")"
));
bytes32 constant internal EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0x213c6f636f3ea94e701c0adf9b2624aa45a6c694f9a292c094f9a81c24b5df4c;
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_DOMAIN_HASH;
// ERC1155Assets(address,uint256[],uint256[],bytes)
bytes4 constant public ERC1155_PROXY_ID = 0xa7cb5fb7;
mapping (bytes32 => bool) public transactions;
address public currentContextAddress;
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
NSignatureTypes // 0x07, number of signature types. Always leave at end.
}
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's state is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// Mapping of orderHash => amount of takerAsset already bought by maker
mapping (bytes32 => uint256) public filled;
// Mapping of orderHash => cancelled
mapping (bytes32 => bool) public cancelled;
mapping (bytes32 => mapping (address => bool)) public preSigned;
// Mapping of makerAddress => senderAddress => lowest salt an order can have in order to be fillable
// Orders with specified senderAddress and with a salt less than their epoch are considered cancelled
mapping (address => mapping (address => uint256)) public orderEpoch;
constructor ()
public
{
EIP712_DOMAIN_HASH = keccak256(
abi.encodePacked(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
uint256(address(this))
));
}
/// @dev Adds properties of both FillResults instances.
/// Modifies the first FillResults instance specified.
/// @param totalFillResults Fill results instance that will be added onto.
/// @param singleFillResults Fill results instance that will be added to totalFillResults.
function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults)
internal
pure
{
totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount);
totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid);
totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid);
}
/// @dev Fills the input order.
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abiEncodeFillOrder(
order,
takerAssetFillAmount,
signature
);
uint256 requiredFee = tx.gasprice * 150000;
require(msg.value >= requiredFee, "PROTOCOL FEE NOT SENT");
// Delegate to `fillOrder` and handle any exceptions gracefully
assembly {
let success := delegatecall(
gas, // forward all gas
address, // call address of this contract
add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes)
mload(fillOrderCalldata), // length of input
fillOrderCalldata, // write output over input
128 // output size is 128 bytes
)
if success {
mstore(fillResults, mload(fillOrderCalldata))
mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32)))
mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64)))
mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96)))
}
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
/// @dev ABI encodes calldata for `fillOrder`.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return ABI encoded calldata for `fillOrder`.
function abiEncodeFillOrder(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
pure
returns (bytes memory fillOrderCalldata)
{
// We need to call MExchangeCore.fillOrder using a delegatecall in
// assembly so that we can intercept a call that throws. For this, we
// need the input encoded in memory in the Ethereum ABIv2 format [1].
// | Area | Offset | Length | Contents |
// | -------- |--------|---------|-------------------------------------------- |
// | Header | 0x00 | 4 | function selector |
// | Params | | 3 * 32 | function parameters: |
// | | 0x00 | | 1. offset to order (*) |
// | | 0x20 | | 2. takerAssetFillAmount |
// | | 0x40 | | 3. offset to signature (*) |
// | Data | | 12 * 32 | order: |
// | | 0x000 | | 1. senderAddress |
// | | 0x020 | | 2. makerAddress |
// | | 0x040 | | 3. takerAddress |
// | | 0x060 | | 4. feeRecipientAddress |
// | | 0x080 | | 5. makerAssetAmount |
// | | 0x0A0 | | 6. takerAssetAmount |
// | | 0x0C0 | | 7. makerFeeAmount |
// | | 0x0E0 | | 8. takerFeeAmount |
// | | 0x100 | | 9. expirationTimeSeconds |
// | | 0x120 | | 10. salt |
// | | 0x140 | | 11. Offset to makerAssetData (*) |
// | | 0x160 | | 12. Offset to takerAssetData (*) |
// | | 0x180 | 32 | makerAssetData Length |
// | | 0x1A0 | ** | makerAssetData Contents |
// | | 0x1C0 | 32 | takerAssetData Length |
// | | 0x1E0 | ** | takerAssetData Contents |
// | | 0x200 | 32 | signature Length |
// | | 0x220 | ** | signature Contents |
// * Offsets are calculated from the beginning of the current area: Header, Params, Data:
// An offset stored in the Params area is calculated from the beginning of the Params section.
// An offset stored in the Data area is calculated from the beginning of the Data section.
// ** The length of dynamic array contents are stored in the field immediately preceeding the contents.
// [1]: https://solidity.readthedocs.io/en/develop/abi-spec.html
assembly {
// Areas below may use the following variables:
// 1. <area>Start -- Start of this area in memory
// 2. <area>End -- End of this area in memory. This value may
// be precomputed (before writing contents),
// or it may be computed as contents are written.
// 3. <area>Offset -- Current offset into area. If an area's End
// is precomputed, this variable tracks the
// offsets of contents as they are written.
/////// Setup Header Area ///////
// Load free memory pointer
fillOrderCalldata := mload(0x40)
// bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)"))
// = 0xb4be83d5
// Leave 0x20 bytes to store the length
mstore(add(fillOrderCalldata, 0x20), 0xb4be83d500000000000000000000000000000000000000000000000000000000)
let headerAreaEnd := add(fillOrderCalldata, 0x24)
/////// Setup Params Area ///////
// This area is preallocated and written to later.
// This is because we need to fill in offsets that have not yet been calculated.
let paramsAreaStart := headerAreaEnd
let paramsAreaEnd := add(paramsAreaStart, 0x60)
let paramsAreaOffset := paramsAreaStart
/////// Setup Data Area ///////
let dataAreaStart := paramsAreaEnd
let dataAreaEnd := dataAreaStart
// Offset from the source data we're reading from
let sourceOffset := order
// arrayLenBytes and arrayLenWords track the length of a dynamically-allocated bytes array.
let arrayLenBytes := 0
let arrayLenWords := 0
/////// Write order Struct ///////
// Write memory location of Order, relative to the start of the
// parameter list, then increment the paramsAreaOffset respectively.
mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart))
paramsAreaOffset := add(paramsAreaOffset, 0x20)
// Write values for each field in the order
// It would be nice to use a loop, but we save on gas by writing
// the stores sequentially.
mstore(dataAreaEnd, mload(sourceOffset)) // makerAddress
mstore(add(dataAreaEnd, 0x20), mload(add(sourceOffset, 0x20))) // takerAddress
mstore(add(dataAreaEnd, 0x40), mload(add(sourceOffset, 0x40))) // feeRecipientAddress
mstore(add(dataAreaEnd, 0x60), mload(add(sourceOffset, 0x60))) // senderAddress
mstore(add(dataAreaEnd, 0x80), mload(add(sourceOffset, 0x80))) // makerAssetAmount
mstore(add(dataAreaEnd, 0xA0), mload(add(sourceOffset, 0xA0))) // takerAssetAmount
mstore(add(dataAreaEnd, 0xC0), mload(add(sourceOffset, 0xC0))) // makerFeeAmount
mstore(add(dataAreaEnd, 0xE0), mload(add(sourceOffset, 0xE0))) // takerFeeAmount
mstore(add(dataAreaEnd, 0x100), mload(add(sourceOffset, 0x100))) // expirationTimeSeconds
mstore(add(dataAreaEnd, 0x120), mload(add(sourceOffset, 0x120))) // salt
mstore(add(dataAreaEnd, 0x140), mload(add(sourceOffset, 0x140))) // Offset to makerAssetData
mstore(add(dataAreaEnd, 0x160), mload(add(sourceOffset, 0x160))) // Offset to takerAssetData
dataAreaEnd := add(dataAreaEnd, 0x180)
sourceOffset := add(sourceOffset, 0x180)
// Write offset to <order.makerAssetData>
mstore(add(dataAreaStart, mul(10, 0x20)), sub(dataAreaEnd, dataAreaStart))
// Calculate length of <order.makerAssetData>
sourceOffset := mload(add(order, 0x140)) // makerAssetData
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of <order.makerAssetData>
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of <order.makerAssetData>
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
// Write offset to <order.takerAssetData>
mstore(add(dataAreaStart, mul(11, 0x20)), sub(dataAreaEnd, dataAreaStart))
// Calculate length of <order.takerAssetData>
sourceOffset := mload(add(order, 0x160)) // takerAssetData
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of <order.takerAssetData>
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of <order.takerAssetData>
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
/////// Write takerAssetFillAmount ///////
mstore(paramsAreaOffset, takerAssetFillAmount)
paramsAreaOffset := add(paramsAreaOffset, 0x20)
/////// Write signature ///////
// Write offset to paramsArea
mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart))
// Calculate length of signature
sourceOffset := signature
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of signature
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of signature
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
// Set length of calldata
mstore(fillOrderCalldata, sub(dataAreaEnd, add(fillOrderCalldata, 0x20)))
// Increment free memory pointer
mstore(0x40, dataAreaEnd)
}
return fillOrderCalldata;
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
nonReentrant
returns (FillResults memory fillResults)
{
uint256 requiredFee = tx.gasprice * 150000;
require(msg.value >= requiredFee, "PROTOCOL FEE NOT SENT");
fillResults = fillOrderInternal(
order,
takerAssetFillAmount,
signature
);
return fillResults;
}
/// @dev Executes an exchange method call in the context of signer.
/// @param salt Arbitrary number to ensure uniqueness of transaction hash.
/// @param signerAddress Address of transaction signer.
/// @param data AbiV2 encoded calldata.
/// @param signature Proof of signer transaction by signer.
function executeTransaction(
uint256 salt,
address signerAddress,
bytes memory data,
bytes memory signature
)
internal
{
// Prevent reentrancy
require(
currentContextAddress == address(0),
"REENTRANCY_ILLEGAL"
);
bytes32 hashedTransaction = hashZeroExTransaction(salt, signerAddress, data);
bytes32 transactionHash = hashEIP712Message(hashedTransaction);
// Validate transaction has not been executed
require(!transactions[transactionHash], "INVALID_TX_HASH");
// Transaction always valid if signer is sender of transaction
if (signerAddress != msg.sender) {
// Validate signature
require(
isValidSignature(
transactionHash,
signerAddress,
signature
),
"INVALID_TX_SIGNATURE"
);
// Set the current transaction signer
currentContextAddress = signerAddress;
}
// Execute transaction
transactions[transactionHash] = true;
(bool success,) = address(this).delegatecall(data);
require(
success,
"FAILED_EXECUTION"
);
// Reset current transaction signer if it was previously updated
if (signerAddress != msg.sender) {
currentContextAddress = address(0);
}
}
/// @dev Updates state with results of a fill order.
/// @param orderTakerAssetFilledAmount Amount of order already filled.
function updateFilledState(
Order memory,
address,
bytes32 orderHash,
uint256 orderTakerAssetFilledAmount,
FillResults memory fillResults
)
internal
{
// Update state
filled[orderHash] = orderTakerAssetFilledAmount.add(fillResults.takerAssetFilledAmount);
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderInternal(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (FillResults memory fillResults)
{
// Fetch order info
OrderInfo memory orderInfo = getOrderInfo(order);
// Fetch taker address
address takerAddress = getCurrentContextAddress();
// Assert that the order is fillable by taker
assertFillableOrder(
order,
orderInfo,
takerAddress,
signature
);
// Get amount of takerAsset to fill
uint256 remainingTakerAssetAmount = order.takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount);
uint256 takerAssetFilledAmount = takerAssetFillAmount.min(remainingTakerAssetAmount);
// Validate context
assertValidFill(
order,
orderInfo,
takerAssetFillAmount,
takerAssetFilledAmount,
fillResults.makerAssetFilledAmount
);
// Compute proportional fill amounts
fillResults = calculateFillResults(order, takerAssetFilledAmount);
// Update exchange internal state
updateFilledState(
order,
takerAddress,
orderInfo.orderHash,
orderInfo.orderTakerAssetFilledAmount,
fillResults
);
// Settle order
settleOrder(
order,
takerAddress,
fillResults
);
return fillResults;
}
/// @dev Validates context for fillOrder. Succeeds or throws.
/// @param order to be filled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
/// @param takerAssetFillAmount Desired amount of order to fill by taker.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param makerAssetFilledAmount Amount of makerAsset that will be transfered.
function assertValidFill(
Order memory order,
OrderInfo memory orderInfo,
uint256 takerAssetFillAmount, // TODO: use FillResults
uint256 takerAssetFilledAmount,
uint256 makerAssetFilledAmount
)
internal
pure
{
// Revert if fill amount is invalid
// TODO: reconsider necessity for v2.1
require(
takerAssetFillAmount != 0,
"INVALID_TAKER_AMOUNT"
);
// Make sure taker does not pay more than desired amount
// NOTE: This assertion should never fail, it is here
// as an extra defence against potential bugs.
require(
takerAssetFilledAmount <= takerAssetFillAmount,
"TAKER_OVERPAY"
);
// Make sure order is not overfilled
// NOTE: This assertion should never fail, it is here
// as an extra defence against potential bugs.
require(
orderInfo.orderTakerAssetFilledAmount.add(takerAssetFilledAmount) <= order.takerAssetAmount,
"ORDER_OVERFILL"
);
// Make sure order is filled at acceptable price.
// The order has an implied price from the makers perspective:
// order price = order.makerAssetAmount / order.takerAssetAmount
// i.e. the number of makerAsset maker is paying per takerAsset. The
// maker is guaranteed to get this price or a better (lower) one. The
// actual price maker is getting in this fill is:
// fill price = makerAssetFilledAmount / takerAssetFilledAmount
// We need `fill price <= order price` for the fill to be fair to maker.
// This amounts to:
// makerAssetFilledAmount order.makerAssetAmount
// ------------------------ <= -----------------------
// takerAssetFilledAmount order.takerAssetAmount
// or, equivalently:
// makerAssetFilledAmount * order.takerAssetAmount <=
// order.makerAssetAmount * takerAssetFilledAmount
// NOTE: This assertion should never fail, it is here
// as an extra defence against potential bugs.
require(
makerAssetFilledAmount.mul(order.takerAssetAmount)
<=
order.makerAssetAmount.mul(takerAssetFilledAmount),
"INVALID_FILL_PRICE"
);
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
Order memory order,
uint256 takerAssetFilledAmount
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = safeGetPartialAmountFloor(
fillResults.makerAssetFilledAmount,
order.makerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
return fillResults;
}
/// @dev Settles an order by transferring assets between counterparties.
/// @param order Order struct containing order specifications.
/// @param takerAddress Address selling takerAsset and buying makerAsset.
/// @param fillResults Amounts to be filled and fees paid by maker and taker.
function settleOrder(
Order memory order,
address takerAddress,
FillResults memory fillResults
)
private
{
dispatchTransferFrom(
order.makerAssetData,
order.makerAddress,
takerAddress,
fillResults.makerAssetFilledAmount
);
dispatchTransferFrom(
order.takerAssetData,
takerAddress,
order.makerAddress,
fillResults.takerAssetFilledAmount
);
}
/// @dev Calculates EIP712 hash of the Transaction.
/// @param salt Arbitrary number to ensure uniqueness of transaction hash.
/// @param signerAddress Address of transaction signer.
/// @param data AbiV2 encoded calldata.
/// @return EIP712 hash of the Transaction.
function hashZeroExTransaction(
uint256 salt,
address signerAddress,
bytes memory data
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes32 dataHash = keccak256(data);
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH,
// salt,
// bytes32(signerAddress),
// keccak256(data)
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 96), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 128)
}
return result;
}
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(Order memory order)
public
view
returns (OrderInfo memory orderInfo)
{
// Compute the order hash
orderInfo.orderHash = getOrderHash(order);
// Fetch filled amount
orderInfo.orderTakerAssetFilledAmount = filled[orderInfo.orderHash];
// If order.makerAssetAmount is zero, we also reject the order.
// While the Exchange contract handles them correctly, they create
// edge cases in the supporting infrastructure because they have
// an 'infinite' price when computed by a simple division.
if (order.makerAssetAmount == 0) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID_MAKER_ASSET_AMOUNT);
return orderInfo;
}
// If order.takerAssetAmount is zero, then the order will always
// be considered filled because 0 == takerAssetAmount == orderTakerAssetFilledAmount
// Instead of distinguishing between unfilled and filled zero taker
// amount orders, we choose not to support them.
if (order.takerAssetAmount == 0) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID_TAKER_ASSET_AMOUNT);
return orderInfo;
}
// Validate order availability
if (orderInfo.orderTakerAssetFilledAmount >= order.takerAssetAmount) {
orderInfo.orderStatus = uint8(OrderStatus.FULLY_FILLED);
return orderInfo;
}
// Validate order expiration
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= order.expirationTimeSeconds) {
orderInfo.orderStatus = uint8(OrderStatus.EXPIRED);
return orderInfo;
}
// Check if order has been cancelled
if (cancelled[orderInfo.orderHash]) {
orderInfo.orderStatus = uint8(OrderStatus.CANCELLED);
return orderInfo;
}
if (orderEpoch[order.makerAddress][order.senderAddress] > order.salt) {
orderInfo.orderStatus = uint8(OrderStatus.CANCELLED);
return orderInfo;
}
// All other statuses are ruled out: order is Fillable
orderInfo.orderStatus = uint8(OrderStatus.FILLABLE);
return orderInfo;
}
/// @dev Calculates Keccak-256 hash of the order.
/// @param order The order structure.
/// @return Keccak-256 EIP712 hash of the order.
function getOrderHash(Order memory order)
internal
view
returns (bytes32 orderHash)
{
orderHash = hashEIP712Message(hashOrder(order));
return orderHash;
}
/// @dev Calculates EIP712 hash of the order.
/// @param order The order structure.
/// @return EIP712 hash of the order.
function hashOrder(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH;
bytes32 makerAssetDataHash = keccak256(order.makerAssetData);
bytes32 takerAssetDataHash = keccak256(order.takerAssetData);
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// bytes32(order.makerAddress),
// bytes32(order.takerAddress),
// bytes32(order.feeRecipientAddress),
// bytes32(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData)
// ));
assembly {
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, makerAssetDataHash)
mstore(pos3, takerAssetDataHash)
result := keccak256(pos1, 416)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to this EIP712 Domain.
function hashEIP712Message(bytes32 hashStruct)
internal
view
returns (bytes32 result)
{
bytes32 eip712DomainHash = EIP712_DOMAIN_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function getCurrentContextAddress()
internal
view
returns (address)
{
address currentContextAddress_ = currentContextAddress;
address contextAddress = currentContextAddress_ == address(0) ? msg.sender : currentContextAddress_;
return contextAddress;
}
/// @dev Validates context for fillOrder. Succeeds or throws.
/// @param order to be filled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
/// @param takerAddress Address of order taker.
/// @param signature Proof that the orders was created by its maker.
function assertFillableOrder(
Order memory order,
OrderInfo memory orderInfo,
address takerAddress,
bytes memory signature
)
internal
view
{
// An order can only be filled if its status is FILLABLE.
require(
orderInfo.orderStatus == uint8(OrderStatus.FILLABLE),
"ORDER_UNFILLABLE"
);
// Validate sender is allowed to fill this order
if (order.senderAddress != address(0)) {
require(
order.senderAddress == msg.sender,
"INVALID_SENDER"
);
}
// Validate taker is allowed to fill this order
if (order.takerAddress != address(0)) {
require(
order.takerAddress == takerAddress,
"INVALID_TAKER"
);
}
// Validate Maker signature (check only if first time seen)
if (orderInfo.orderTakerAssetFilledAmount == 0) {
require(
isValidSignature(
orderInfo.orderHash,
order.makerAddress,
signature
),
"INVALID_ORDER_SIGNATURE"
);
}
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorFloor(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount =
numerator.mul(target).div(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.mul(1000) >= numerator.mul(target);
return isError;
}
/// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws.
/// @param assetData Byte array encoded for the asset.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param amount Amount of token to transfer.
function dispatchTransferFrom(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// Do nothing if no amount should be transferred.
if (amount > 0 && from != to) {
// Ensure assetData length is valid
require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
address assetProxy = address(this);
// We construct calldata for the `assetProxy.transferFrom` ABI.
// The layout of this calldata is in the table below.
//
// | Area | Offset | Length | Contents |
// | -------- |--------|---------|-------------------------------------------- |
// | Header | 0 | 4 | function selector |
// | Params | | 4 * 32 | function parameters: |
// | | 4 | | 1. offset to assetData (*) |
// | | 36 | | 2. from |
// | | 68 | | 3. to |
// | | 100 | | 4. amount |
// | Data | | | assetData: |
// | | 132 | 32 | assetData Length |
// | | 164 | ** | assetData Contents |
assembly {
/////// Setup State ///////
// `cdStart` is the start of the calldata for `assetProxy.transferFrom` (equal to free memory ptr).
let cdStart := mload(64)
// `dataAreaLength` is the total number of words needed to store `assetData`
// As-per the ABI spec, this value is padded up to the nearest multiple of 32,
// and includes 32-bytes for length.
let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0)
// `cdEnd` is the end of the calldata for `assetProxy.transferFrom`.
let cdEnd := add(cdStart, add(132, dataAreaLength))
/////// Setup Header Area ///////
// This area holds the 4-byte `transferFromSelector`.
// bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000)
/////// Setup Params Area ///////
// Each parameter is padded to 32-bytes. The entire Params Area is 128 bytes.
// Notes:
// 1. The offset to `assetData` is the length of the Params Area (128 bytes).
// 2. A 20-byte mask is applied to addresses to zero-out the unused bytes.
mstore(add(cdStart, 4), 128)
mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(cdStart, 100), amount)
/////// Setup Data Area ///////
// This area holds `assetData`.
let dataArea := add(cdStart, 132)
// solhint-disable-next-line no-empty-blocks
for {} lt(dataArea, cdEnd) {} {
mstore(dataArea, mload(assetData))
dataArea := add(dataArea, 32)
assetData := add(assetData, 32)
}
/////// Call `assetProxy.transferFrom` using the constructed calldata ///////
let success := call(
gas, // forward all gas
assetProxy, // call address of asset proxy
0, // don't send any ETH
cdStart, // pointer to start of input
sub(cdEnd, cdStart), // length of input
cdStart, // write output over input
512 // reserve 512 bytes for output
)
if iszero(success) {
revert(cdStart, returndatasize())
}
}
}
}
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32 byte hash.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return True if the address recovered from the provided signature matches the input signer address.
function isValidSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid)
{
require(
signature.length > 0,
"LENGTH_GREATER_THAN_0_REQUIRED"
);
// Pop last byte off of signature byte array.
uint8 signatureTypeRaw = uint8(popLastByte(signature));
// Ensure signature is supported
require(
signatureTypeRaw < uint8(SignatureType.NSignatureTypes),
"SIGNATURE_UNSUPPORTED"
);
SignatureType signatureType = SignatureType(signatureTypeRaw);
// Variables are not scoped in Solidity.
uint8 v;
bytes32 r;
bytes32 s;
address recovered;
// Always illegal signature.
// This is always an implicit option since a signer can create a
// signature array with invalid type or length. We may as well make
// it an explicit option. This aids testing and analysis. It is
// also the initialization value for the enum type.
if (signatureType == SignatureType.Illegal) {
revert("SIGNATURE_ILLEGAL");
// Always invalid signature.
// Like Illegal, this is always implicitly available and therefore
// offered explicitly. It can be implicitly created by providing
// a correctly formatted but incorrect signature.
} else if (signatureType == SignatureType.Invalid) {
require(
signature.length == 0,
"LENGTH_0_REQUIRED"
);
isValid = false;
return isValid;
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
v = uint8(signature[0]);
r = readBytes32(signature, 1);
s = readBytes32(signature, 33);
recovered = ecrecover(
hash,
v,
r,
s
);
isValid = signerAddress == recovered;
return isValid;
// Signed using web3.eth_sign
} else if (signatureType == SignatureType.EthSign) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
v = uint8(signature[0]);
r = readBytes32(signature, 1);
s = readBytes32(signature, 33);
recovered = ecrecover(
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
v,
r,
s
);
isValid = signerAddress == recovered;
return isValid;
// Signature verified by wallet contract.
// If used with an order, the maker of the order is the wallet contract.
} else if (signatureType == SignatureType.Wallet) {
isValid = isValidWalletSignature(
hash,
signerAddress,
signature
);
return isValid;
// Signer signed hash previously using the preSign function.
} else if (signatureType == SignatureType.PreSigned) {
isValid = preSigned[hash][signerAddress];
return isValid;
}
// Anything else is illegal (We do not return false because
// the signature may actually be valid, just not in a format
// that we currently support. In this case returning false
// may lead the caller to incorrectly believe that the
// signature was invalid.)
revert("SIGNATURE_UNSUPPORTED");
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
"GREATER_THAN_ZERO_LENGTH_REQUIRED"
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Verifies signature using logic defined by Wallet contract.
/// @param hash Any 32 byte hash.
/// @param walletAddress Address that should have signed the given hash
/// and defines its own signature verification method.
/// @param signature Proof that the hash has been signed by signer.
/// @return True if signature is valid for given wallet..
function isValidWalletSignature(
bytes32 hash,
address walletAddress,
bytes memory signature
)
internal
view
returns (bool isValid)
{
bytes memory callData = abi.encodeWithSelector(
IWallet(walletAddress).isValidSignature.selector,
hash,
signature
);
assembly {
let cdStart := add(callData, 32)
let success := staticcall(
gas, // forward all gas
walletAddress, // address of Wallet contract
cdStart, // pointer to start of input
mload(callData), // length of input
cdStart, // write output over input
32 // output size is 32 bytes
)
switch success
case 0 {
// Revert with `Error("WALLET_ERROR")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000000c57414c4c45545f4552524f5200000000000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
case 1 {
// Signature is valid if call did not revert and returned true
isValid := mload(cdStart)
}
}
return isValid;
}
/// @dev Transfers assets. Either succeeds or throws.
/// @param assetData Encoded byte array.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external
{
require(msg.sender == address(this));
transferFromInternal(
assetData,
from,
to,
amount
);
}
/// @dev Transfers batch of ERC1155 assets. Either succeeds or throws.
/// @param assetData Byte array encoded with ERC1155 token address, array of ids, array of values, and callback data.
/// @param from Address to transfer assets from.
/// @param to Address to transfer assets to.
/// @param amount Amount that will be multiplied with each element of `assetData.values` to scale the
/// values that will be transferred.
function transferFromInternal(
bytes memory assetData,
address from,
address to,
uint256 amount
)
private
{
// Decode params from `assetData`
(address erc1155TokenAddress, uint256[] memory ids, uint256[] memory values, bytes memory data) = abi.decode(sliceDestructive(assetData, 4, assetData.length), (address, uint256[], uint256[], bytes));
// Scale values up by `amount`
uint256 length = values.length;
uint256[] memory scaledValues = new uint256[](length);
for (uint256 i = 0; i != length; i++) {
// We write the scaled values to an unused location in memory in order
// to avoid copying over `ids` or `data`. This is possible if they are
// identical to `values` and the offsets for each are pointing to the
// same location in the ABI encoded calldata.
scaledValues[i] = values[i].mul(amount);
}
// Execute `safeBatchTransferFrom` call
// Either succeeds or throws
IERC1155(erc1155TokenAddress).safeBatchTransferFrom(
from,
to,
ids,
scaledValues,
data
);
}
/// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets.
/// @return The ERC-1155 AssetProxy identifier, the address of the ERC-1155
/// contract hosting the assets, an array of the identifiers of the
/// assets to be traded, an array of asset amounts to be traded, and
/// callback data. Each element of the arrays corresponds to the
/// same-indexed element of the other array. Return values specified as
/// `memory` are returned as pointers to locations within the memory of
/// the input parameter `assetData`.
function decodeERC1155AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
uint256[] memory tokenIds,
uint256[] memory tokenValues,
bytes memory callbackData
)
{
assetProxyId = readBytes4(assetData, 0);
require(
assetProxyId == ERC1155_PROXY_ID,
"WRONG_PROXY_ID"
);
assembly {
// Skip selector and length to get to the first parameter:
assetData := add(assetData, 36)
// Read the value of the first parameter:
tokenAddress := mload(assetData)
// Point to the next parameter's data:
tokenIds := add(assetData, mload(add(assetData, 32)))
// Point to the next parameter's data:
tokenValues := add(assetData, mload(add(assetData, 64)))
// Point to the next parameter's data:
callbackData := add(assetData, mload(add(assetData, 96)))
}
return (
assetProxyId,
tokenAddress,
tokenIds,
tokenValues,
callbackData
);
}
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
public
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev After calling, the order can not be filled anymore.
/// Throws if order is invalid or sender does not have permission to cancel.
/// @param order Order to cancel. Order must be OrderStatus.FILLABLE.
function cancelOrder(Order memory order)
public
nonReentrant
{
cancelOrderInternal(order);
}
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orders Array of order specifications.
function batchCancelOrders(Order[] memory orders)
public
nonReentrant
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
cancelOrderInternal(orders[i]);
}
}
/// @dev After calling, the order can not be filled anymore.
/// Throws if order is invalid or sender does not have permission to cancel.
/// @param order Order to cancel. Order must be OrderStatus.FILLABLE.
function cancelOrderInternal(Order memory order)
internal
{
// Fetch current order status
OrderInfo memory orderInfo = getOrderInfo(order);
// Validate context
assertValidCancel(order, orderInfo);
// Perform cancel
updateCancelledState(order, orderInfo.orderHash);
}
/// @dev Validates context for cancelOrder. Succeeds or throws.
/// @param order to be cancelled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
function assertValidCancel(
Order memory order,
OrderInfo memory orderInfo
)
internal
view
{
// Ensure order is valid
// An order can only be cancelled if its status is FILLABLE.
require(
orderInfo.orderStatus == uint8(OrderStatus.FILLABLE),
"ORDER_UNFILLABLE"
);
// Validate sender is allowed to cancel this order
if (order.senderAddress != address(0)) {
require(
order.senderAddress == msg.sender,
"INVALID_SENDER"
);
}
// Validate transaction signed by maker
address makerAddress = getCurrentContextAddress();
require(
order.makerAddress == makerAddress,
"INVALID_MAKER"
);
}
/// @dev Updates state with results of cancelling an order.
/// State is only updated if the order is currently fillable.
/// Otherwise, updating state would have no effect.
/// @param order that was cancelled.
/// @param orderHash Hash of order that was cancelled.
function updateCancelledState(
Order memory order,
bytes32 orderHash
)
internal
{
// Perform cancel
cancelled[orderHash] = true;
}
}
|
Fills the input order. Returns false if the transaction would otherwise revert. order Order struct containing order specifications. takerAssetFillAmount Desired amount of takerAsset to sell. signature Proof that order has been created by maker. return Amounts filled and fees paid by maker and taker. ABI encode calldata for `fillOrder` Delegate to `fillOrder` and handle any exceptions gracefully
|
function fillOrderNoThrow(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (FillResults memory fillResults)
{
bytes memory fillOrderCalldata = abiEncodeFillOrder(
order,
takerAssetFillAmount,
signature
);
uint256 requiredFee = tx.gasprice * 150000;
require(msg.value >= requiredFee, "PROTOCOL FEE NOT SENT");
assembly {
let success := delegatecall(
)
if success {
mstore(fillResults, mload(fillOrderCalldata))
mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32)))
mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64)))
mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96)))
}
}
}
| 5,479,144
|
/**
*Submitted for verification at Etherscan.io on 2021-04-05
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: @openzeppelin/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: @openzeppelin/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @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.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
// File: contracts/Token.sol
pragma solidity 0.5.0;
contract Token is ERC20, ERC20Detailed, ERC20Burnable, ERC20Mintable, ERC20Pausable, ERC20Capped {
uint256 public _startTime;
uint256 public _mintCliff;
uint256 public _tokensMintedInQuarter;
uint256 public _maxMintPerQuarter;
uint256 public _lastMintTime;
uint256 public _tokensMintedTotal;
uint256 public _tokensMintCap;
constructor(
uint256 initialSupply,
uint256 startTime,
uint256 mintCliff,
uint256 maxMintPerQuarter,
uint256 tokensMintCap
)
public
ERC20Detailed(
"Delta Exchange Token",
"DETO",
18
)
ERC20Capped(750*(10**6)*(10**18))
{
_startTime = startTime;
_mintCliff = mintCliff;
_maxMintPerQuarter = maxMintPerQuarter;
_tokensMintCap = tokensMintCap;
_tokensMintedTotal = initialSupply;
_mint(msg.sender, initialSupply);
}
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
require(block.timestamp >= _startTime.add(_mintCliff), "No minting allowed before mint cliff");
require(_tokensMintedTotal.add(amount) <= _tokensMintCap, "Mint cap reached");
uint256 quarterStartTime = getQuarterStartTime();
uint256 maxMintable = getMaxMintable(quarterStartTime);
require(amount <= maxMintable, "Limit exceeded for minting this quarter");
if( _lastMintTime < quarterStartTime ){
_tokensMintedInQuarter = amount;
} else{
_tokensMintedInQuarter = _tokensMintedInQuarter.add(amount);
}
_lastMintTime = block.timestamp;
_tokensMintedTotal = _tokensMintedTotal.add(amount);
_mint(account, amount);
return true;
}
function getQuarterStartTime() public view returns (uint256){
uint256 cliffEndTime = _startTime.add(_mintCliff);
if( block.timestamp < cliffEndTime ){
return cliffEndTime;
} else{
uint256 quarter = 0.25*(365 days);
return cliffEndTime + ((block.timestamp - cliffEndTime)/(quarter))*(quarter);
}
}
function getMaxMintable(uint256 quarterStartTime) public view returns (uint256){
if( _lastMintTime < quarterStartTime ){
return _maxMintPerQuarter;
} else{
return _maxMintPerQuarter - _tokensMintedInQuarter;
}
}
}
// File: contracts/Vesting.sol
pragma solidity 0.5.0;
/**
* @title Vesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period
*/
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
contract Vesting {
using SafeMath for uint256;
address private owner;
Token private token;
uint256 private unreleasedTokens;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
struct Grant {
uint256 duration;
uint256 cliff;
}
mapping (address => uint256 ) private startTimes;
mapping (address => uint256) private amounts;
mapping (address => uint256) private releasedTokens;
mapping (address => bytes32 ) private beneficiaryGrant;
mapping (bytes32 => Grant) private grants;
event tokensVested(address indexed _to, uint256 _amount, bytes32 _grantName);
event tokensReleased(address indexed _invoker, address indexed _beneficiary, uint256 _amount);
event grantAdded(bytes32 _grantName, uint256 _cliff, uint256 _duration);
modifier onlyOwner { require(msg.sender == owner); _; }
constructor(address tokenAddress) public {
token = Token(tokenAddress);
owner = msg.sender;
}
function addVestingGrant(bytes32 grantName, uint256 cliff, uint256 duration) onlyOwner external {
require(cliff >= 0, "TokenVesting: cliff is negative");
require(duration >= 0, "TokenVesting: duration is negative");
Grant memory grant = Grant({
duration: duration,
cliff: cliff
});
grants[grantName] = grant;
emit grantAdded(grantName, cliff, duration);
}
function vestTokens(
address beneficiary,
uint256 amount,
bytes32 grantName,
uint256 startTime
)
onlyOwner
external
{
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
require(amounts[beneficiary] == 0, "TokenVesting: beneficiary already exists");
Grant memory grant = grants[grantName];
require(
startTime.add(grant.cliff).add(grant.duration) > block.timestamp,
"TokenVesting: final time is before current time"
);
unreleasedTokens = unreleasedTokens.add(amount);
uint256 contractTokens = token.balanceOf(address(this));
require(
unreleasedTokens <= contractTokens,
"TokenVesting: Total amount allocated should be less than tokens in contract"
);
startTimes[beneficiary] = startTime;
amounts[beneficiary] = amount;
beneficiaryGrant[beneficiary] = grantName;
emit tokensVested(beneficiary, amount, grantName);
}
/**
* @return the start time of the token vesting.
*/
function startTime(address beneficiary) external view returns (uint256) {
return startTimes[beneficiary];
}
/**
* @return the cliff time of the token vesting.
*/
function cliff(address beneficiary) external view returns (uint256) {
bytes32 grantName = beneficiaryGrant[beneficiary];
return grants[grantName].cliff;
}
/**
* @return the duration of the token vesting.
*/
function duration(address beneficiary) external view returns (uint256) {
bytes32 grantName = beneficiaryGrant[beneficiary];
return grants[grantName].duration;
}
/**
* @return the amount of the tokens alloted .
*/
function amount(address beneficiary) external view returns (uint256) {
return amounts[beneficiary];
}
/**
* @return the amount of the token released.
*/
function releasedAmount(address beneficiary) external view returns (uint256) {
return releasedTokens[beneficiary];
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release(address beneficiary) external {
require(
msg.sender == owner || msg.sender == beneficiary,
"TokenVesting: Tokens can be released only by owner or beneficiary"
);
uint256 unreleased = releasableAmount(beneficiary);
require(unreleased > 0, "TokenVesting: no tokens are due");
releasedTokens[beneficiary] = releasedTokens[beneficiary].add(unreleased);
unreleasedTokens = unreleasedTokens.sub(unreleased);
token.transfer(beneficiary, unreleased);
emit tokensReleased(msg.sender, beneficiary, unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount(address beneficiary) public view returns (uint256) {
return vestedAmount(beneficiary).sub(releasedTokens[beneficiary]);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount(address beneficiary) public view returns (uint256) {
uint256 totalAmount = amounts[beneficiary];
bytes32 grantName = beneficiaryGrant[beneficiary];
Grant memory grant = grants[grantName];
uint256 start = startTimes[beneficiary];
if (block.timestamp < start.add(grant.cliff)) {
return 0;
} else if (block.timestamp >= start.add(grant.cliff).add(grant.duration)) {
return totalAmount;
} else {
return totalAmount.mul(block.timestamp.sub(start.add(grant.cliff))).div(grant.duration);
}
}
}
|
Transfers vested tokens to beneficiary./
|
function release(address beneficiary) external {
require(
msg.sender == owner || msg.sender == beneficiary,
"TokenVesting: Tokens can be released only by owner or beneficiary"
);
uint256 unreleased = releasableAmount(beneficiary);
require(unreleased > 0, "TokenVesting: no tokens are due");
releasedTokens[beneficiary] = releasedTokens[beneficiary].add(unreleased);
unreleasedTokens = unreleasedTokens.sub(unreleased);
token.transfer(beneficiary, unreleased);
emit tokensReleased(msg.sender, beneficiary, unreleased);
}
| 10,749,933
|
./partial_match/42/0x6B22626b8B33d57cC245A3B9a095Eb9ED2AEF723/sources/UberHausMinion.sol
|
only collect if 1) there are tokens to collect and 2) token is whitelisted in the Moloch (child dao)
|
function collectTokens(address token) external {
uint256 totalBalance = (userTokenBalances[GUILD][token]) + (userTokenBalances[REWARDS][token]);
uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - totalBalance;
require(amountToCollect > 0, "no tokens");
require(moloch.tokenWhitelist(token), "not whitelisted");
if (token == HAUS){
splitHAUS(amountToCollect);
unsafeAddToBalance(GUILD, token, amountToCollect);
}
emit TokensCollected(token, amountToCollect);
}
| 3,309,989
|
./partial_match/1/0x9EbD236E6B974E1a7411eC0Cd33bD12576cdBbc5/sources/OwnedUpgradeabilityProxy.sol
|
Tells the address of the implementation where every call will be delegated. Should be implemented in a descendant contract return address of the implementation to which it will be delegated/
|
function implementation() public view returns (address) {
assert(false);
}
| 4,317,870
|
./full_match/5/0xd24e6Ff54E08Ac3Bb2A3765b67e07F1670b46Dfa/sources/contracts/ERC20Upgradeable.sol
|
Emitted when a `denylister` denylists a `denylistee`./ Emitted when `denylister` undenylists a `denylistee`./ Emitted when `denylister` destroys funds of a `denylistee`./ Returns true if the high bit of the balance is set to 1 indicating denylisting, and false otherwise./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
event Denylist(address indexed denylister, address indexed denylistee);
event Undenylist(address indexed denylister, address indexed denylistee);
event DestroyDenylistedFunds(
address indexed denylister,
address indexed denylistee,
uint256 indexed amount
);
function _isBalanceDenylisted(uint256 userBalance)
internal
view
virtual
returns (bool)
{
return userBalance >> 255 == 1;
}
| 7,057,290
|
// This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20)
// You can find more complex example in https://github.com/ConsenSys/Tokens
pragma solidity ^0.4.8;
import "./BaseToken.sol";
import "./SafeMath.sol";
contract MisoToken is BaseToken {
using SafeMath for uint;
using SafeMath for uint256;
// Standard Solidity Interface
string public name;
uint8 public decimals;
string public symbol;
string public version = "MISO";
// MISO Token Specific
address owner;
// How many MISO tokens are given daily
uint256 public dailyTokens = 12;
// How many MISO tokens are used per feed
uint256 public tokensPerFeed = 3;
// When did you last claim your tokens
mapping (address => uint) lastClaimed;
// Feeding history
mapping (address => uint[]) feedingHistory;
// How many blocks before you can claim tokens
uint public blocksPerClaim = 100;
// Callback function everytime someone feeds an address
// https://solidity.readthedocs.io/en/v0.4.21/contracts.html#events
event feedEvent(address addr);
function UsableToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
owner = msg.sender;
balances[this] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function changeBlocksPerClaim(uint newB) public {
require(msg.sender == owner);
blocksPerClaim = newB;
}
function getBlocksTillClaimable(address addr) public view returns (uint blockNo) {
if (lastClaimed[addr] == 0) {
return 0;
}
uint blockDif = (block.number - lastClaimed[addr] - 1);
if (blockDif < blocksPerClaim) {
return blocksPerClaim.sub(blockDif);
}
return 0;
}
function getLastClaimBlock(address addr) public view returns (uint blockNo) {
return lastClaimed[addr];
}
function getFeedingHistory (address addr) public view returns (uint[]) {
return feedingHistory[addr];
}
function getBlocksPerClaim () public view returns (uint) {
return blocksPerClaim;
}
function getTokensPerFeed () public view returns (uint) {
return tokensPerFeed;
}
function getDailyTokensNo () public view returns (uint) {
return dailyTokens;
}
function getClaimableTokens (address addr) public view returns (uint) {
uint value;
if (lastClaimed[addr] == 0) {
// Initial claim = set to current block number
value = dailyTokens;
} else {
// How many mutiples of food
uint multiples = (block.number - lastClaimed[addr] - 1).div(blocksPerClaim);
value = multiples * dailyTokens;
}
return value;
}
function claim() public returns (bool success) {
// Can only claim tokens every 5k blocks
if (block.number - lastClaimed[msg.sender] - 1 < blocksPerClaim) {
return false;
}
uint value;
if (lastClaimed[msg.sender] == 0) {
// Initial claim = set to current block number
value = dailyTokens;
} else {
// How many mutiples of food
uint multiples = (block.number - lastClaimed[msg.sender] - 1).div(blocksPerClaim);
value = multiples * dailyTokens;
}
lastClaimed[msg.sender] = block.number - 1;
balances[msg.sender] += value;
balances[this] -= value;
Transfer(this, msg.sender, value);
return true;
}
function feed() public {
require(balances[msg.sender] >= tokensPerFeed);
// Add to feeding history
feedingHistory[msg.sender].push(block.number - 1);
balances[msg.sender] -= tokensPerFeed;
balances[this] += tokensPerFeed;
emit feedEvent(msg.sender);
}
}
|
Add to feeding history
|
function feed() public {
require(balances[msg.sender] >= tokensPerFeed);
feedingHistory[msg.sender].push(block.number - 1);
balances[msg.sender] -= tokensPerFeed;
balances[this] += tokensPerFeed;
emit feedEvent(msg.sender);
}
| 954,141
|
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @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(uint a, uint b) internal pure returns (bool, uint) {
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
// 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);
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint 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, uint 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,
uint 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,
uint value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @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 uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @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,
uint 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint 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/protocol/IStrategyETH_V3.sol
/*
version 1.3.0
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- remove functions that are not called by other contracts (vaults and controller)
*/
interface IStrategyETH_V3 {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying token (ETH or ERC20)
@dev Return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying token transferred from vault
*/
function totalDebt() external view returns (uint);
/*
@notice Returns amount of underlying token locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Deposit ETH
*/
function deposit() external payable;
/*
@notice Withdraw `_amount` underlying token
@param amount Amount of underlying token to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying token from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying
*/
function harvest() external;
/*
@notice Increase total debt if totalAssets > totalDebt
*/
function skim() external;
/*
@notice Exit from strategy, transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/StrategyETH_V3.sol
/*
Changes
- remove functions related to slippage and delta
- add keeper
- remove _increaseDebt
- remove _decreaseDebt
*/
// used inside harvest
abstract contract StrategyETH_V3 is IStrategyETH_V3 {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
// Placeholder address to indicate that this is ETH strategy
address public constant override underlying =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// some functions specific to strategy cannot be called by controller
// so we introduce a new role
address public keeper;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// Force exit, in case normal exit fails
bool public forceExit;
constructor(
address _controller,
address _vault,
address _keeper
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_keeper != address(0), "keeper = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
keeper = _keeper;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin ||
msg.sender == controller ||
msg.sender == vault ||
msg.sender == keeper,
"!authorized"
);
_;
}
function setAdmin(address _admin) external onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setKeeper(address _keeper) external onlyAdmin {
require(_keeper != address(0), "keeper = zero address");
keeper = _keeper;
}
function setPerformanceFee(uint _fee) external onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setForceExit(bool _forceExit) external onlyAdmin {
forceExit = _forceExit;
}
function totalAssets() external view virtual override returns (uint);
function deposit() external payable virtual override;
function withdraw(uint) external virtual override;
function withdrawAll() external virtual override;
function harvest() external virtual override;
function skim() external virtual override;
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/compound/CEth.sol
interface CEth {
function mint() external payable;
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function redeem(uint) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function balanceOfUnderlying(address account) external returns (uint);
function getAccountSnapshot(address account)
external
view
returns (
uint,
uint,
uint,
uint
);
}
// File: contracts/interfaces/compound/Comptroller.sol
interface Comptroller {
function markets(address cToken)
external
view
returns (
bool,
uint,
bool
);
// Claim all the COMP accrued by holder in all markets
function claimComp(address holder) external;
// TODO: use this to save gas?
// Claim all the COMP accrued by holder in specific markets
function claimComp(address holder, address[] calldata cTokens) external;
}
// File: contracts/strategies/StrategyCompLevEth.sol
/*
APY estimate
c = collateral ratio
i_s = supply interest rate (APY)
i_b = borrow interest rate (APY)
c_s = supply COMP reward (APY)
c_b = borrow COMP reward (APY)
leverage APY = 1 / (1 - c) * (i_s + c_s - c * (i_b - c_b))
plugging some numbers
31.08 = 4 * (7.01 + 4 - 0.75 * (9.08 - 4.76))
*/
/*
State transitions and valid transactions
### State ###
buff = buffer
s = supplied
b = borrowed
### Transactions ###
dl = deleverage
l = leverage
w = withdraw
d = deposit
s(x) = set butter to x
### State Transitions ###
s(max)
(buf = max, s > 0, b > 0) <--------- (buf = min, s > 0, b > 0)
| | ^
| dl, w | dl, w | l, d
| | |
V V |
(buf = max, s > 0, b = 0) ---------> (buf = min, s > 0, b = 0)
s(min)
*/
contract StrategyCompLevEth is StrategyETH_V3 {
event Deposit(uint amount);
event Withdraw(uint amount);
event Harvest(uint profit);
event Skim(uint profit);
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Compound //
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private immutable cToken;
// buffer to stay below market collateral ratio, scaled up by 1e18
uint public buffer = 0.04 * 1e18;
constructor(
address _controller,
address _vault,
address _cToken,
address _keeper
) public StrategyETH_V3(_controller, _vault, _keeper) {
require(_cToken != address(0), "cToken = zero address");
cToken = _cToken;
// These tokens are never held by this contract
// so the risk of them getting stolen is minimal
IERC20(COMP).safeApprove(UNISWAP, type(uint).max);
}
receive() external payable {
// Don't allow vault to accidentally send ETH
require(msg.sender != vault, "msg.sender = vault");
}
function _sendEthToVault(uint _amount) private {
(bool sent, ) = vault.call{value: _amount}("");
require(sent, "Send ETH failed");
}
function _increaseDebt(uint _amount) private {
totalDebt = totalDebt.add(_amount);
}
function _decreaseDebt(uint _amount) private {
if (_amount >= totalDebt) {
totalDebt = 0;
} else {
totalDebt -= _amount;
}
_sendEthToVault(_amount);
}
function _totalAssets() private view returns (uint) {
// WARNING: This returns balance last time someone transacted with cToken
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
if (error > 0) {
// something is wrong, return 0
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
// something is wrong, return 0
return 0;
}
uint bal = address(this).balance;
// supplied >= borrowed
return bal.add(supplied - borrowed);
}
/*
@notice Returns amount of ETH locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
/*
@dev buffer = 0 means safe collateral ratio = market collateral ratio
buffer = 1e18 means safe collateral ratio = 0
*/
function setBuffer(uint _buffer) external onlyAuthorized {
require(_buffer > 0 && _buffer <= 1e18, "buffer");
buffer = _buffer;
}
function _getMarketCollateralRatio() private view returns (uint) {
/*
This can be changed by Compound Governance, with a minimum waiting
period of five days
*/
(, uint col, ) = Comptroller(COMPTROLLER).markets(cToken);
return col;
}
function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) {
if (_marketCol > buffer) {
return _marketCol - buffer;
}
return 0;
}
// Not view function
function _getSupplied() private returns (uint) {
return CEth(cToken).balanceOfUnderlying(address(this));
}
// Not view function
function _getBorrowed() private returns (uint) {
return CEth(cToken).borrowBalanceCurrent(address(this));
}
// Not view function. Call using static call from web3
function getLivePosition()
external
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
supplied = _getSupplied();
borrowed = _getBorrowed();
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
// @dev This returns balance last time someone transacted with cToken
function getCachedPosition()
external
view
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
// ignore first output, which is error code
(, uint cTokenBal, uint _borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
supplied = cTokenBal.mul(exchangeRate) / 1e18;
borrowed = _borrowed;
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
// @dev This modifier checks collateral ratio after leverage or deleverage
modifier checkCollateralRatio() {
_;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
// borrowed / supplied <= safe col
// supplied can = 0 so we check borrowed <= supplied * safe col
// max borrow
uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
}
function _supply(uint _amount) private {
CEth(cToken).mint{value: _amount}();
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of ETH
function supply(uint _amount) external onlyAdmin {
_supply(_amount);
}
function _borrow(uint _amount) private {
require(CEth(cToken).borrow(_amount) == 0, "borrow");
}
// @dev Execute manual recovery by admin
function borrow(uint _amount) external onlyAdmin {
_borrow(_amount);
}
function _repay(uint _amount) private {
CEth(cToken).repayBorrow{value: _amount}();
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of ETH
function repay(uint _amount) external onlyAdmin {
_repay(_amount);
}
function _redeem(uint _amount) private {
require(CEth(cToken).redeemUnderlying(_amount) == 0, "redeem");
}
// @dev Execute manual recovery by admin
function redeem(uint _amount) external onlyAdmin {
_redeem(_amount);
}
function _getMaxLeverageRatio(uint _col) private pure returns (uint) {
/*
c = collateral ratio
geometric series converges to
1 / (1 - c)
*/
// multiplied by 1e18
return uint(1e36).div(uint(1e18).sub(_col));
}
function _getBorrowAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
x = amount to borrow
(b + x) / s <= c
becomes
x <= sc - b
*/
// max borrow
uint max = _supplied.mul(_col) / 1e18;
if (_borrowed >= max) {
return 0;
}
return max - _borrowed;
}
/*
Find total supply S_n after n iterations starting with
S_0 supplied and B_0 borrowed
c = collateral ratio
S_i = supplied after i iterations
B_i = borrowed after i iterations
S_0 = current supplied
B_0 = current borrowed
borrowed and supplied after n iterations
B_n = cS_(n-1)
S_n = S_(n-1) + (cS_(n-1) - B_(n-1))
you can prove using algebra and induction that
B_n / S_n <= c
S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0)
S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1
= S_0 + (1 - c^n) / (1 - c)
S_n <= S_0 + (cS_0 - B_0) / (1 - c)
*/
function _leverage(uint _targetSupply) private checkCollateralRatio {
// buffer = 1e18 means safe collateral ratio = 0
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed); // supply with 0 leverage
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
// 99% to be safe, and save gas
uint max = (unleveraged.mul(lev) / 1e18).mul(9900) / 10000;
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
// target is usually reached in 9 iterations
require(i < 25, "max iteration");
// use market collateral to calculate borrow amount
// this is done so that supplied can reach _targetSupply
// 99.99% is borrowed to be safe
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
// borrow > 0 since supplied < _targetSupply
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
// end loop with _supply, this ensures no borrowed amount is unutilized
_supply(borrowAmount);
// supplied > _getSupplied(), by about 3 * 1e12 %, but we use local variable to save gas
supplied = supplied.add(borrowAmount);
// _getBorrowed == borrowed
borrowed = borrowed.add(borrowAmount);
i++;
}
}
function leverage(uint _targetSupply) external onlyAuthorized {
_leverage(_targetSupply);
}
function _deposit() private {
uint bal = address(this).balance;
if (bal > 0) {
_supply(bal);
// leverage to max
_leverage(type(uint).max);
}
}
/*
@notice Deposit ETH into this strategy
*/
function deposit() external payable override onlyAuthorized {
require(msg.value > 0, "deposit = 0");
_increaseDebt(msg.value);
_deposit();
emit Deposit(msg.value);
}
function _getRedeemAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
r = redeem
b / (s - r) <= c
becomes
r <= s - b / c
*/
// min supply
// b / c = min supply needed to borrow b
uint min = _borrowed.mul(1e18).div(_col);
if (_supplied <= min) {
return 0;
}
return _supplied - min;
}
/*
Find S_0, amount of supply with 0 leverage, after n iterations starting with
S_n supplied and B_n borrowed
c = collateral ratio
S_n = current supplied
B_n = current borrowed
S_(n-i) = supplied after i iterations
B_(n-i) = borrowed after i iterations
R_(n-i) = Redeemable after i iterations
= S_(n-i) - B_(n-i) / c
where B_(n-i) / c = min supply needed to borrow B_(n-i)
For 0 <= k <= n - 1
S_k = S_(k+1) - R_(k+1)
B_k = B_(k+1) - R_(k+1)
and
S_k - B_k = S_(k+1) - B_(k+1)
so
S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n
S_0 has 0 leverage so B_0 = 0 and we get
S_0 = S_0 - B_0 = S_n - B_n
------------------------------------------
Find S_(n-k), amount of supply, after k iterations starting with
S_n supplied and B_n borrowed
with algebra and induction you can derive that
R_(n-k) = R_n / c^k
S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1
= S_n - R_n * ((1 - 1/c^k) / (1 - 1/c))
Equation above is valid for S_(n - k) k < n
*/
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
// min supply
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
// target is usually reached in 8 iterations
require(i < 25, "max iteration");
// 99.99% to be safe
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
// redeem > 0 since supplied > _targetSupply
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
// supplied < _geSupplied(), by about 7 * 1e12 %
supplied = supplied.sub(redeemAmount);
// borrowed == _getBorrowed()
borrowed = borrowed.sub(redeemAmount);
i++;
}
}
function deleverage(uint _targetSupply) external onlyAuthorized {
_deleverage(_targetSupply);
}
// @dev Returns amount available for transfer
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
/*
c = collateral ratio
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
*/
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
// r <= s - b
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
// cr / (1 - c) <= x <= b
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
/*
@notice Withdraw undelying token to vault
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _amount) external override onlyAuthorized {
require(_amount > 0, "withdraw = 0");
// available <= _amount
uint available = _withdraw(_amount);
if (available > 0) {
_decreaseDebt(available);
}
emit Withdraw(available);
}
// @dev withdraw all creates dust in supplied
function _withdrawAll() private {
_withdraw(type(uint).max);
// In case there is dust, re-calculate balance
uint bal = address(this).balance;
if (bal > 0) {
_sendEthToVault(bal);
totalDebt = 0;
}
emit Withdraw(bal);
}
/*
@notice Withdraw all ETH to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swapToEth(address _from, uint _amount) private {
// create dynamic array with 2 elements
address[] memory path = new address[](2);
path[0] = _from;
path[1] = WETH;
Uniswap(UNISWAP).swapExactTokensForETH(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards() private {
// claim COMP
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
Comptroller(COMPTROLLER).claimComp(address(this), cTokens);
uint compBal = IERC20(COMP).balanceOf(address(this));
if (compBal > 0) {
_swapToEth(COMP, compBal);
// Now this contract has ETH
}
}
/*
@notice Claim and sell any rewards
*/
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
// treasury must be able to receive ETH
(bool sent, ) = treasury.call{value: fee}("");
require(sent, "Send ETH failed");
}
// _supply() to decrease collateral ratio and earn interest
// use _supply() instead of _deposit() to save gas
uint profit = bal.sub(fee);
_supply(profit);
emit Harvest(profit);
}
}
/*
@notice Increase total debt if profit > 0
*/
function skim() external override onlyAuthorized {
uint bal = address(this).balance;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
uint total = bal.add(unleveraged);
require(total > totalDebt, "total <= debt");
uint profit = total - totalDebt;
// Incrementing totalDebt has the same effect as transferring profit
// back to vault and then depositing into this strategy
// Here we simply increment totalDebt to save gas
totalDebt = total;
emit Skim(profit);
}
/*
@notice Exit from strategy, transfer all ETH back to vault
unless forceExit = true
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
*/
function sweep(address _token) external override onlyAdmin {
require(_token != cToken, "protected token");
require(_token != COMP, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
|
Returns amount available for transfer r <= s - b
|
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
| 2,382,375
|
pragma solidity ^0.4.23;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Adminable.sol
/**
* @title Adminable
* @dev The adminable contract has an admin address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Adminable is Ownable {
address public admin;
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
/**
* @dev The Mintable constructor sets the original `minter` of the contract to the sender
* account.
*/
constructor() public {
admin = msg.sender;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == admin, "Only admin is allowed to execute this method.");
_;
}
/**
* @dev Allows the current owner to transfer control of the admin to newAdmin
*/
function transferAdmin(address newAdmin) public onlyOwner {
require(newAdmin != address(0));
emit AdminTransferred(admin, newAdmin);
admin = newAdmin;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(
address indexed _from,
address indexed _to,
uint256 _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: contracts/EpicsToken.sol
contract EpicsToken is ERC721Token("Epics.gg Token", "EPICS TOKEN"), Ownable, Adminable {
event TokenLock(string uuid); // Single token trade locked
event TokenUnlock(string uuid); // Single token trade unlocked
event UserVerified(string userToken, address userAddress); // User sends this to verify their eth account
event TokenCreated(string uuid, address to);
event TokenDestroyed(string uuid);
event TokenOwnerSet(address from, address to, string uuid);
event TradingLock(); // Globally locked
event TradingUnlock(); // Globally unlocked
struct Token {
string uuid;
string properties;
}
mapping (string => uint256) private uuidToTokenId; // Maps UUID to token id
mapping (string => bool) private uuidExists; // Checking if UUID exists
mapping (uint256 => bool) private lockedTokens; // Prevent certain tokens from being traded
bool public tradingLocked; // Prevent all trading?
Token[] tokens; // Keeps track of our array of Token structs
/**
* @dev Gets the owner of the specified token UUID
*/
function ownerOfUUID(string _uuid) public view returns (address) {
require(uuidExists[_uuid] == true, "UUID does not exist."); // Enable these when Truffle updates solc to 0.4.23
uint256 _tokenId = uuidToTokenId[_uuid];
return ownerOf(_tokenId);
}
/**
* @dev Gets the token id for the specified UUID
*/
function tokenIdOfUUID(string _uuid) public view returns (uint256) {
require(uuidExists[_uuid] == true, "UUID does not exist.");
return uuidToTokenId[_uuid];
}
/**
* Returns the token data associated with a token id
*/
function getToken(uint256 _tokenId) public view returns (string uuid, string properties) {
require(exists(_tokenId), "Token does not exist.");
Token memory token = tokens[_tokenId];
uuid = token.uuid;
properties = token.properties;
}
function isTokenLocked(uint256 _tokenId) public view returns (bool) {
require(exists(_tokenId), "Token does not exist.");
return lockedTokens[_tokenId];
}
function verifyUser(string userToken) public returns (bool) {
emit UserVerified(userToken, msg.sender);
return true;
}
function tokensByOwner(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
// ------------------------------------------------------------------------------------------------------
// Only Owner functionality below here
/**
* @dev Lock all trading of tokens.
*/
function lockTrading() public onlyAdmin {
require(tradingLocked == false, "Trading already locked.");
tradingLocked = true;
emit TradingLock();
}
/**
* @dev Unlock trading. If there were some tokens individually locked, this will not unlock them.
*/
function unlockTrading() public onlyAdmin {
require(tradingLocked == true, "Trading already unlocked.");
tradingLocked = false;
emit TradingUnlock();
}
// ------------------------------------------------------------------------------------------------------
// Only Admin functionality below here
/**
* @dev Create a token and give to address.
*/
function createToken(string _uuid, string _properties, address _to) public onlyAdmin {
require(uuidExists[_uuid] == false, "UUID already exists.");
Token memory _token = Token({uuid: _uuid, properties: _properties});
uint256 _tokenId = tokens.push(_token) - 1;
uuidToTokenId[_uuid] = _tokenId;
uuidExists[_uuid] = true;
lockedTokens[_tokenId] = true;
_mint(_to, _tokenId);
emit TokenCreated(_uuid, _to);
}
/**
* Update a token (such as it's treatment or designation or skin)
*/
function updateToken(string _uuid, string _properties) public onlyAdmin {
require(uuidExists[_uuid] == true, "UUID does not exist.");
uint256 _tokenId = uuidToTokenId[_uuid];
Token memory _token = Token({uuid: _uuid, properties: _properties});
tokens[_tokenId] = _token;
}
function destroyToken(uint256 _tokenId) public onlyAdmin {
require(exists(_tokenId), "Token does not exist.");
require(lockedTokens[_tokenId] == true, "Token must be locked before being destroyed.");
Token memory _token = tokens[_tokenId];
delete uuidExists[_token.uuid];
delete uuidToTokenId[_token.uuid];
delete lockedTokens[_tokenId];
_burn(ownerOf(_tokenId), _tokenId);
emit TokenDestroyed(_token.uuid);
}
/**
* @dev Lock a token to prevent it from being traded.
*/
function lockToken(address _owner, uint256 _tokenId) public onlyAdmin {
require(exists(_tokenId), "Token does not exist.");
require(lockedTokens[_tokenId] == false, "Token is already locked.");
require(ownerOf(_tokenId) == _owner, "The owner has changed since it was suppose to be locked.");
lockedTokens[_tokenId] = true;
Token memory _token = tokens[_tokenId];
emit TokenLock(_token.uuid);
}
/**
* @dev Unlock a token so it can be traded.
*/
function unlockToken(address _owner, uint256 _tokenId) public onlyAdmin {
require(exists(_tokenId), "Token does not exist.");
require(lockedTokens[_tokenId] == true, "Token is already unlocked.");
require(ownerOf(_tokenId) == _owner, "The owner has changed since it was suppose to be locked.");
lockedTokens[_tokenId] = false;
Token memory _token = tokens[_tokenId];
emit TokenUnlock(_token.uuid);
}
/**
* @dev When cards are moved around in the app, this will update their ownership on the block chain.
* Tokens must be locked by admin for this.
*/
function setOwner(address _to, uint256 _tokenId) public onlyAdmin {
require(exists(_tokenId), "Token does not exist.");
require(lockedTokens[_tokenId] == true || tradingLocked == true, "Token must be locked before owner is changed.");
address _owner = ownerOf(_tokenId);
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
addTokenTo(_to, _tokenId);
Token memory _token = tokens[_tokenId];
emit TokenOwnerSet(_owner, _to, _token.uuid);
emit Transfer(_owner, _to, _tokenId);
}
// ------------------------------------------------------------------------------------------------------
// These are wrapper functions to enable locked tokens, locked trading
function transferFrom(address _from, address _to, uint256 _tokenId) public {
require(tradingLocked == false && lockedTokens[_tokenId] == false, "Token must be unlocked to be transferred.");
super.transferFrom(_from, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public {
require(tradingLocked == false && lockedTokens[_tokenId] == false, "Token must be unlocked to be approved.");
super.approve(_to, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) public {
require(tradingLocked == false, "Token must be unlocked to be approved for all.");
super.setApprovalForAll(_operator, _approved);
}
}
|
Create a token and give to address./
|
function createToken(string _uuid, string _properties, address _to) public onlyAdmin {
require(uuidExists[_uuid] == false, "UUID already exists.");
uint256 _tokenId = tokens.push(_token) - 1;
uuidToTokenId[_uuid] = _tokenId;
uuidExists[_uuid] = true;
lockedTokens[_tokenId] = true;
_mint(_to, _tokenId);
emit TokenCreated(_uuid, _to);
}
| 10,971,735
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../interfaces/AccessControlledInterface.sol";
import "../vendor/AccessControllerInterface.sol";
import "../vendor/ConfirmedOwner.sol";
contract AccessControlled is AccessControlledInterface, ConfirmedOwner(msg.sender) {
AccessControllerInterface internal s_accessController;
function setAccessController(
AccessControllerInterface _accessController
)
public
override
onlyOwner()
{
require(address(_accessController) != address(s_accessController), "Access controller is already set");
s_accessController = _accessController;
emit AccessControllerSet(address(_accessController), msg.sender);
}
function getAccessController()
public
view
override
returns (
AccessControllerInterface
)
{
return s_accessController;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../vendor/AccessControllerInterface.sol";
interface AccessControlledInterface {
event AccessControllerSet(
address indexed accessController,
address indexed sender
);
function setAccessController(
AccessControllerInterface _accessController
)
external;
function getAccessController()
external
view
returns (
AccessControllerInterface
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.6.0 <0.8.0;
interface AccessControllerInterface {
function hasAccess(address user, bytes calldata data) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ConfirmedOwnerWithProposal.sol";
/**
* @title The ConfirmedOwner contract
* @notice A contract with helpers for basic contract ownership.
*/
contract ConfirmedOwner is ConfirmedOwnerWithProposal {
constructor(
address newOwner
)
ConfirmedOwnerWithProposal(
newOwner,
address(0)
)
{
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../interfaces/OwnableInterface.sol";
/**
* @title The ConfirmedOwner contract
* @notice A contract with helpers for basic contract ownership.
*/
contract ConfirmedOwnerWithProposal is OwnableInterface {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor(
address owner,
address pendingOwner
) {
require(owner != address(0), "Cannot set owner to zero");
s_owner = owner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/**
* @notice Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(
address to
)
public
override
onlyOwner()
{
_transferOwnership(to);
}
/**
* @notice Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
override
{
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @notice Get the current owner
*/
function owner()
public
view
override
returns (
address
)
{
return s_owner;
}
/**
* @notice validate, transfer ownership, and emit relevant events
*/
function _transferOwnership(
address to
)
private
{
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/**
* @notice validate access
*/
function _validateOwnership()
internal
{
require(msg.sender == s_owner, "Only callable by owner");
}
/**
* @notice Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
_validateOwnership();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface OwnableInterface {
function owner()
external
returns (
address
);
function transferOwnership(
address recipient
)
external;
function acceptOwnership()
external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2; // solhint-disable compiler-version
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol";
import "./access/AccessControlled.sol";
import "./interfaces/FeedRegistryInterface.sol";
/**
* @notice An on-chain registry of assets to aggregators.
* @notice This contract provides a consistent address for consumers but delegates where it reads from to the owner, who is
* trusted to update it. This registry contract works for multiple feeds, not just a single aggregator.
* @notice Only access enabled addresses are allowed to access getters for answers and round data
*/
contract FeedRegistry is FeedRegistryInterface, AccessControlled {
uint256 constant private PHASE_OFFSET = 64;
uint256 constant private PHASE_SIZE = 16;
uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1;
mapping(address => bool) private s_isAggregatorEnabled;
mapping(address => mapping(address => AggregatorV2V3Interface)) private s_proposedAggregators;
mapping(address => mapping(address => uint16)) private s_currentPhaseId;
mapping(address => mapping(address => mapping(uint16 => AggregatorV2V3Interface))) private s_phaseAggregators;
mapping(address => mapping(address => mapping(uint16 => Phase))) private s_phases;
/*
* @notice Versioning
*/
function typeAndVersion()
external
override
pure
virtual
returns (
string memory
)
{
return "FeedRegistry 1.0.0-alpha";
}
/**
* @notice represents the number of decimals the aggregator responses represent.
*/
function decimals(
address asset,
address denomination
)
external
view
override
returns (
uint8
)
{
AggregatorV2V3Interface aggregator = _getFeed(asset, denomination);
return aggregator.decimals();
}
/**
* @notice returns the description of the aggregator the proxy points to.
*/
function description(
address asset,
address denomination
)
external
view
override
returns (
string memory
)
{
AggregatorV2V3Interface aggregator = _getFeed(asset, denomination);
return aggregator.description();
}
/**
* @notice the version number representing the type of aggregator the proxy
* points to.
*/
function version(
address asset,
address denomination
)
external
view
override
returns (
uint256
)
{
AggregatorV2V3Interface aggregator = _getFeed(asset, denomination);
return aggregator.version();
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param asset asset address
* @param denomination denomination address
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with a phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function latestRoundData(
address asset,
address denomination
)
external
view
override
checkPairAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination);
(
roundId,
answer,
startedAt,
updatedAt,
answeredInRound
) = currentPhaseAggregator.latestRoundData();
return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, currentPhaseId);
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param asset asset address
* @param denomination denomination address
* @param _roundId the proxy round id number to retrieve the round data for
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with a phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function getRoundData(
address asset,
address denomination,
uint80 _roundId
)
external
view
override
checkPairAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
(uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(_roundId);
AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId);
(
roundId,
answer,
startedAt,
updatedAt,
answeredInRound
) = aggregator.getRoundData(aggregatorRoundId);
return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, phaseId);
}
/**
* @notice Reads the current answer for an asset / denomination pair's aggregator.
* @param asset asset address
* @param denomination denomination address
* @notice We advise to use latestRoundData() instead because it returns more in-depth information.
* @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer(
address asset,
address denomination
)
external
view
override
checkPairAccess()
returns (
int256 answer
)
{
AggregatorV2V3Interface aggregator = _getFeed(asset, denomination);
return aggregator.latestAnswer();
}
/**
* @notice get the latest completed timestamp where the answer was updated.
* @param asset asset address
* @param denomination denomination address
*
* @notice We advise to use latestRoundData() instead because it returns more in-depth information.
* @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp(
address asset,
address denomination
)
external
view
override
checkPairAccess()
returns (
uint256 timestamp
)
{
AggregatorV2V3Interface aggregator = _getFeed(asset, denomination);
return aggregator.latestTimestamp();
}
/**
* @notice get the latest completed round where the answer was updated
* @param asset asset address
* @param denomination denomination address
* @dev overridden function to add the checkAccess() modifier
*
* @notice We advise to use latestRoundData() instead because it returns more in-depth information.
* @dev Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound(
address asset,
address denomination
)
external
view
override
checkPairAccess()
returns (
uint256 roundId
)
{
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination);
return _addPhase(currentPhaseId, uint64(currentPhaseAggregator.latestRound()));
}
/**
* @notice get past rounds answers
* @param asset asset address
* @param denomination denomination address
* @param roundId the proxy round id number to retrieve the answer for
* @dev overridden function to add the checkAccess() modifier
*
* @notice We advise to use getRoundData() instead because it returns more in-depth information.
* @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(
address asset,
address denomination,
uint256 roundId
)
external
view
override
checkPairAccess()
returns (
int256 answer
)
{
if (roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId);
AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId);
if (address(aggregator) == address(0)) return 0;
return aggregator.getAnswer(aggregatorRoundId);
}
/**
* @notice get block timestamp when an answer was last updated
* @param asset asset address
* @param denomination denomination address
* @param roundId the proxy round id number to retrieve the updated timestamp for
* @dev overridden function to add the checkAccess() modifier
*
* @notice We advise to use getRoundData() instead because it returns more in-depth information.
* @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(
address asset,
address denomination,
uint256 roundId
)
external
view
override
checkPairAccess()
returns (
uint256 timestamp
)
{
if (roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId);
AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId);
if (address(aggregator) == address(0)) return 0;
return aggregator.getTimestamp(aggregatorRoundId);
}
/**
* @notice Retrieve the aggregator of an asset / denomination pair in the current phase
* @param asset asset address
* @param denomination denomination address
* @return aggregator
*/
function getFeed(
address asset,
address denomination
)
public
view
override
returns (
AggregatorV2V3Interface aggregator
)
{
aggregator = _getFeed(asset, denomination);
require(address(aggregator) != address(0), "Feed not found");
}
/**
* @notice retrieve the aggregator of an asset / denomination pair at a specific phase
* @param asset asset address
* @param denomination denomination address
* @param phaseId phase ID
* @return aggregator
*/
function getPhaseFeed(
address asset,
address denomination,
uint16 phaseId
)
public
view
override
returns (
AggregatorV2V3Interface aggregator
)
{
aggregator = _getPhaseFeed(asset, denomination, phaseId);
require(address(aggregator) != address(0), "Feed not found for phase");
}
/**
* @notice returns true if a aggregator is enabled for any pair
* @param aggregator aggregator address
*/
function isFeedEnabled(
address aggregator
)
public
view
override
returns (
bool
)
{
return s_isAggregatorEnabled[aggregator];
}
/**
* @notice returns a phase by id. A Phase contains the starting and ending aggregator round ids.
* endingAggregatorRoundId will be 0 if the phase is the current phase
* @dev reverts if the phase does not exist
* @param asset asset address
* @param denomination denomination address
* @param phaseId phase id
* @return phase
*/
function getPhase(
address asset,
address denomination,
uint16 phaseId
)
public
view
override
returns (
Phase memory phase
)
{
phase = _getPhase(asset, denomination, phaseId);
require(_phaseExists(phase), "Phase does not exist");
}
/**
* @notice retrieve the aggregator of an asset / denomination pair at a specific round id
* @param asset asset address
* @param denomination denomination address
* @param roundId the proxy round id
*/
function getRoundFeed(
address asset,
address denomination,
uint80 roundId
)
public
view
override
returns (
AggregatorV2V3Interface aggregator
)
{
uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId);
aggregator = _getPhaseFeed(asset, denomination, phaseId);
require(address(aggregator) != address(0), "Feed not found for round");
}
/**
* @notice returns the range of proxy round ids of a phase
* @param asset asset address
* @param denomination denomination address
* @param phaseId phase id
* @return startingRoundId
* @return endingRoundId
*/
function getPhaseRange(
address asset,
address denomination,
uint16 phaseId
)
public
view
override
returns (
uint80 startingRoundId,
uint80 endingRoundId
)
{
Phase memory phase = _getPhase(asset, denomination, phaseId);
require(_phaseExists(phase), "Phase does not exist");
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
if (phaseId == currentPhaseId) return _getLatestRoundRange(asset, denomination, currentPhaseId);
return _getPhaseRange(asset, denomination, phaseId);
}
/**
* @notice return the previous round id of a given round
* @param asset asset address
* @param denomination denomination address
* @param roundId the round id number to retrieve the updated timestamp for
* @dev Note that this is not the aggregator round id, but the proxy round id
* To get full ranges of round ids of different phases, use getPhaseRange()
* @return previousRoundId
*/
function getPreviousRoundId(
address asset,
address denomination,
uint80 roundId
) external
view
override
returns (
uint80 previousRoundId
)
{
uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId);
return _getPreviousRoundId(asset, denomination, phaseId, roundId);
}
/**
* @notice return the next round id of a given round
* @param asset asset address
* @param denomination denomination address
* @param roundId the round id number to retrieve the updated timestamp for
* @dev Note that this is not the aggregator round id, but the proxy round id
* To get full ranges of round ids of different phases, use getPhaseRange()
* @return nextRoundId
*/
function getNextRoundId(
address asset,
address denomination,
uint80 roundId
) external
view
override
returns (
uint80 nextRoundId
)
{
uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId);
return _getNextRoundId(asset, denomination, phaseId, roundId);
}
/**
* @notice Allows the owner to propose a new address for the aggregator
* @param asset asset address
* @param denomination denomination address
* @param aggregator The new aggregator contract address
*/
function proposeFeed(
address asset,
address denomination,
address aggregator
)
external
override
onlyOwner()
{
AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination);
require(aggregator != address(currentPhaseAggregator), "Cannot propose current aggregator");
address proposedAggregator = address(_getProposedFeed(asset, denomination));
if (proposedAggregator != aggregator) {
s_proposedAggregators[asset][denomination] = AggregatorV2V3Interface(aggregator);
emit FeedProposed(asset, denomination, aggregator, address(currentPhaseAggregator), msg.sender);
}
}
/**
* @notice Allows the owner to confirm and change the address
* to the proposed aggregator
* @dev Reverts if the given address doesn't match what was previously
* proposed
* @param asset asset address
* @param denomination denomination address
* @param aggregator The new aggregator contract address
*/
function confirmFeed(
address asset,
address denomination,
address aggregator
)
external
override
onlyOwner()
{
(uint16 nextPhaseId, address previousAggregator) = _setFeed(asset, denomination, aggregator);
s_isAggregatorEnabled[aggregator] = true;
s_isAggregatorEnabled[previousAggregator] = false;
emit FeedConfirmed(asset, denomination, aggregator, previousAggregator, nextPhaseId, msg.sender);
}
/**
* @notice Returns the proposed aggregator for an asset / denomination pair
* returns a zero address if there is no proposed aggregator for the pair
* @param asset asset address
* @param denomination denomination address
* @return proposedAggregator
*/
function getProposedFeed(
address asset,
address denomination
)
public
view
override
returns (
AggregatorV2V3Interface proposedAggregator
)
{
return _getProposedFeed(asset, denomination);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @param asset asset address
* @param denomination denomination address
* @param roundId the round ID to retrieve the round data for
* @return id is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedGetRoundData(
address asset,
address denomination,
uint80 roundId
)
external
view
virtual
override
hasProposal(asset, denomination)
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return s_proposedAggregators[asset][denomination].getRoundData(roundId);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @param asset asset address
* @param denomination denomination address
* @return id is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedLatestRoundData(
address asset,
address denomination
)
external
view
virtual
override
hasProposal(asset, denomination)
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return s_proposedAggregators[asset][denomination].latestRoundData();
}
function getCurrentPhaseId(
address asset,
address denomination
)
public
view
override
returns (
uint16 currentPhaseId
)
{
return s_currentPhaseId[asset][denomination];
}
function _addPhase(
uint16 phase,
uint64 originalId
)
internal
pure
returns (
uint80
)
{
return uint80(uint256(phase) << PHASE_OFFSET | originalId);
}
function _parseIds(
uint256 roundId
)
internal
pure
returns (
uint16,
uint64
)
{
uint16 phaseId = uint16(roundId >> PHASE_OFFSET);
uint64 aggregatorRoundId = uint64(roundId);
return (phaseId, aggregatorRoundId);
}
function _addPhaseIds(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound,
uint16 phaseId
)
internal
pure
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
return (
_addPhase(phaseId, uint64(roundId)),
answer,
startedAt,
updatedAt,
_addPhase(phaseId, uint64(answeredInRound))
);
}
function _getPhase(
address asset,
address denomination,
uint16 phaseId
)
internal
view
returns (
Phase memory phase
)
{
return s_phases[asset][denomination][phaseId];
}
function _phaseExists(
Phase memory phase
)
internal
pure
returns (
bool
)
{
return phase.phaseId > 0;
}
function _getProposedFeed(
address asset,
address denomination
)
internal
view
returns (
AggregatorV2V3Interface proposedAggregator
)
{
return s_proposedAggregators[asset][denomination];
}
function _getPhaseFeed(
address asset,
address denomination,
uint16 phaseId
)
internal
view
returns (
AggregatorV2V3Interface aggregator
)
{
return s_phaseAggregators[asset][denomination][phaseId];
}
function _getFeed(
address asset,
address denomination
)
internal
view
returns (
AggregatorV2V3Interface aggregator
)
{
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
return _getPhaseFeed(asset, denomination, currentPhaseId);
}
function _setFeed(
address asset,
address denomination,
address newAggregator
)
internal
returns (
uint16 nextPhaseId,
address previousAggregator
)
{
require(newAggregator == address(s_proposedAggregators[asset][denomination]), "Invalid proposed aggregator");
delete s_proposedAggregators[asset][denomination];
AggregatorV2V3Interface currentAggregator = _getFeed(asset, denomination);
uint80 previousAggregatorEndingRoundId = _getLatestAggregatorRoundId(currentAggregator);
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
s_phases[asset][denomination][currentPhaseId].endingAggregatorRoundId = previousAggregatorEndingRoundId;
nextPhaseId = currentPhaseId + 1;
s_currentPhaseId[asset][denomination] = nextPhaseId;
s_phaseAggregators[asset][denomination][nextPhaseId] = AggregatorV2V3Interface(newAggregator);
uint80 startingRoundId = _getLatestAggregatorRoundId(AggregatorV2V3Interface(newAggregator));
s_phases[asset][denomination][nextPhaseId] = Phase(nextPhaseId, startingRoundId, 0);
return (nextPhaseId, address(currentAggregator));
}
function _getPreviousRoundId(
address asset,
address denomination,
uint16 phaseId,
uint80 roundId
)
internal
view
returns (
uint80
)
{
for (uint16 pid = phaseId; pid > 0; pid--) {
AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid);
(uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid);
if (address(phaseAggregator) == address(0)) continue;
if (roundId <= startingRoundId) continue;
if (roundId > startingRoundId && roundId <= endingRoundId) return roundId - 1;
if (roundId > endingRoundId) return endingRoundId;
}
return 0; // Round not found
}
function _getNextRoundId(
address asset,
address denomination,
uint16 phaseId,
uint80 roundId
)
internal
view
returns (
uint80
)
{
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
for (uint16 pid = phaseId; pid <= currentPhaseId; pid++) {
AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid);
(uint80 startingRoundId, uint80 endingRoundId) =
(pid == currentPhaseId) ? _getLatestRoundRange(asset, denomination, pid) : _getPhaseRange(asset, denomination, pid);
if (address(phaseAggregator) == address(0)) continue;
if (roundId >= endingRoundId) continue;
if (roundId >= startingRoundId && roundId < endingRoundId) return roundId + 1;
if (roundId < startingRoundId) return startingRoundId;
}
return 0; // Round not found
}
function _getPhaseRange(
address asset,
address denomination,
uint16 phaseId
)
internal
view
returns (
uint80 startingRoundId,
uint80 endingRoundId
)
{
Phase memory phase = _getPhase(asset, denomination, phaseId);
return (
_getStartingRoundId(phaseId, phase),
_getEndingRoundId(phaseId, phase)
);
}
function _getLatestRoundRange(
address asset,
address denomination,
uint16 currentPhaseId
)
internal
view
returns (
uint80 startingRoundId,
uint80 endingRoundId
)
{
Phase memory phase = s_phases[asset][denomination][currentPhaseId];
return (
_getStartingRoundId(currentPhaseId, phase),
_getLatestRoundId(asset, denomination, currentPhaseId)
);
}
function _getStartingRoundId(
uint16 phaseId,
Phase memory phase
)
internal
pure
returns (
uint80 startingRoundId
)
{
return _addPhase(phaseId, uint64(phase.startingAggregatorRoundId));
}
function _getEndingRoundId(
uint16 phaseId,
Phase memory phase
)
internal
pure
returns (
uint80 startingRoundId
)
{
return _addPhase(phaseId, uint64(phase.endingAggregatorRoundId));
}
function _getLatestRoundId(
address asset,
address denomination,
uint16 currentPhaseId
)
internal
view
returns (
uint80 startingRoundId
)
{
AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination);
uint80 latestAggregatorRoundId = _getLatestAggregatorRoundId(currentPhaseAggregator);
return _addPhase(currentPhaseId, uint64(latestAggregatorRoundId));
}
function _getLatestAggregatorRoundId(
AggregatorV2V3Interface aggregator
)
internal
view
returns (
uint80 roundId
)
{
if (address(aggregator) == address(0)) return uint80(0);
return uint80(aggregator.latestRound());
}
function _getPhaseIdByRoundId(
address asset,
address denomination,
uint80 roundId
)
internal
view
returns (
uint16 phaseId
)
{
// Handle case where the round is in current phase
uint16 currentPhaseId = s_currentPhaseId[asset][denomination];
(uint80 startingCurrentRoundId, uint80 endingCurrentRoundId) = _getLatestRoundRange(asset, denomination, currentPhaseId);
if (roundId >= startingCurrentRoundId && roundId <= endingCurrentRoundId) return currentPhaseId;
// Handle case where the round is in past phases
for (uint16 pid = currentPhaseId - 1; pid > 0; pid--) {
AggregatorV2V3Interface phaseAggregator = s_phaseAggregators[asset][denomination][pid];
if (address(phaseAggregator) == address(0)) continue;
(uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid);
if (roundId >= startingRoundId && roundId <= endingRoundId) return pid;
if (roundId > endingRoundId) break;
}
return 0;
}
/**
* @dev reverts if the caller does not have access granted by the accessController contract
* to the asset / denomination pair or is the contract itself.
*/
modifier checkPairAccess() {
require(address(s_accessController) == address(0) || s_accessController.hasAccess(msg.sender, msg.data), "No access");
_;
}
/**
* @dev reverts if no proposed aggregator was set
*/
modifier hasProposal(
address asset,
address denomination
) {
require(address(s_proposedAggregators[asset][denomination]) != address(0), "No proposed aggregator present");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2; // solhint-disable compiler-version
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol";
import "./AccessControlledInterface.sol";
import "./TypeAndVersionInterface.sol";
interface FeedRegistryInterface is AccessControlledInterface, TypeAndVersionInterface {
struct Phase {
uint16 phaseId;
uint80 startingAggregatorRoundId; // The latest round id of `aggregator` at phase start
uint80 endingAggregatorRoundId; // The latest round of the at phase end
}
event FeedProposed(
address indexed asset,
address indexed denomination,
address indexed proposedAggregator,
address currentAggregator,
address sender
);
event FeedConfirmed(
address indexed asset,
address indexed denomination,
address indexed latestAggregator,
address previousAggregator,
uint16 nextPhaseId,
address sender
);
// V3 AggregatorV3Interface
function decimals(
address asset,
address denomination
)
external
view
returns (
uint8
);
function description(
address asset,
address denomination
)
external
view
returns (
string memory
);
function version(
address asset,
address denomination
)
external
view
returns (
uint256
);
function latestRoundData(
address asset,
address denomination
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(
address asset,
address denomination,
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// V2 AggregatorInterface
function latestAnswer(
address asset,
address denomination
)
external
view
returns (
int256 answer
);
function latestTimestamp(
address asset,
address denomination
)
external
view
returns (
uint256 timestamp
);
function latestRound(
address asset,
address denomination
)
external
view
returns (
uint256 roundId
);
function getAnswer(
address asset,
address denomination,
uint256 roundId
)
external
view
returns (
int256 answer
);
function getTimestamp(
address asset,
address denomination,
uint256 roundId
)
external
view
returns (
uint256 timestamp
);
// Registry getters
function getFeed(
address asset,
address denomination
)
external
view
returns (
AggregatorV2V3Interface aggregator
);
function getPhaseFeed(
address asset,
address denomination,
uint16 phaseId
)
external
view
returns (
AggregatorV2V3Interface aggregator
);
function isFeedEnabled(
address aggregator
)
external
view
returns (
bool
);
function getPhase(
address asset,
address denomination,
uint16 phaseId
)
external
view
returns (
Phase memory phase
);
// Round helpers
function getRoundFeed(
address asset,
address denomination,
uint80 roundId
)
external
view
returns (
AggregatorV2V3Interface aggregator
);
function getPhaseRange(
address asset,
address denomination,
uint16 phaseId
)
external
view
returns (
uint80 startingRoundId,
uint80 endingRoundId
);
function getPreviousRoundId(
address asset,
address denomination,
uint80 roundId
) external
view
returns (
uint80 previousRoundId
);
function getNextRoundId(
address asset,
address denomination,
uint80 roundId
) external
view
returns (
uint80 nextRoundId
);
// Feed management
function proposeFeed(
address asset,
address denomination,
address aggregator
) external;
function confirmFeed(
address asset,
address denomination,
address aggregator
) external;
// Proposed aggregator
function getProposedFeed(
address asset,
address denomination
)
external
view
returns (
AggregatorV2V3Interface proposedAggregator
);
function proposedGetRoundData(
address asset,
address denomination,
uint80 roundId
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData(
address asset,
address denomination
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// Phases
function getCurrentPhaseId(
address asset,
address denomination
)
external
view
returns (
uint16 currentPhaseId
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface TypeAndVersionInterface{
function typeAndVersion()
external
pure
returns (
string memory
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../interfaces/FeedRegistryInterface.sol";
contract MockConsumer {
FeedRegistryInterface private s_FeedRegistry;
constructor(
FeedRegistryInterface FeedRegistry
) {
s_FeedRegistry = FeedRegistry;
}
function getFeedRegistry()
public
view
returns (
FeedRegistryInterface
)
{
return s_FeedRegistry;
}
function read(
address asset,
address denomination
)
public
view
returns (
int256
)
{
return s_FeedRegistry.latestAnswer(asset, denomination);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../vendor/AccessControllerInterface.sol";
import "../vendor/ConfirmedOwner.sol";
/**
* @title WriteAccessController
* @notice Has two access lists: a global list and a data-specific list.
* @dev does not make any special permissions for EOAs, see
* ReadAccessController for that.
*/
contract WriteAccessController is AccessControllerInterface, ConfirmedOwner(msg.sender) {
bool private s_checkEnabled = true;
mapping(address => bool) internal s_globalAccessList;
mapping(address => mapping(bytes => bool)) internal s_localAccessList;
event AccessAdded(address user, bytes data, address sender);
event AccessRemoved(address user, bytes data, address sender);
event CheckAccessEnabled();
event CheckAccessDisabled();
function checkEnabled()
public
view
returns (
bool
)
{
return s_checkEnabled;
}
/**
* @notice Returns the access of an address
* @param user The address to query
* @param data The calldata to query
*/
function hasAccess(
address user,
bytes memory data
)
public
view
virtual
override
returns (bool)
{
return !s_checkEnabled || s_globalAccessList[user] || s_localAccessList[user][data];
}
/**
* @notice Adds an address to the global access list
* @param user The address to add
*/
function addGlobalAccess(
address user
)
external
onlyOwner()
{
_addGlobalAccess(user);
}
/**
* @notice Adds an address+data to the local access list
* @param user The address to add
* @param data The calldata to add
*/
function addLocalAccess(
address user,
bytes memory data
)
external
onlyOwner()
{
_addLocalAccess(user, data);
}
/**
* @notice Removes an address from the global access list
* @param user The address to remove
*/
function removeGlobalAccess(
address user
)
external
onlyOwner()
{
_removeGlobalAccess(user);
}
/**
* @notice Removes an address+data from the local access list
* @param user The address to remove
* @param data The calldata to remove
*/
function removeLocalAccess(
address user,
bytes memory data
)
external
onlyOwner()
{
_removeLocalAccess(user, data);
}
/**
* @notice makes the access check enforced
*/
function enableAccessCheck()
external
onlyOwner()
{
_enableAccessCheck();
}
/**
* @notice makes the access check unenforced
*/
function disableAccessCheck()
external
onlyOwner()
{
_disableAccessCheck();
}
/**
* @dev reverts if the caller does not have access
*/
modifier checkAccess() {
if (s_checkEnabled) {
require(hasAccess(msg.sender, msg.data), "No access");
}
_;
}
function _enableAccessCheck() internal {
if (!s_checkEnabled) {
s_checkEnabled = true;
emit CheckAccessEnabled();
}
}
function _disableAccessCheck() internal {
if (s_checkEnabled) {
s_checkEnabled = false;
emit CheckAccessDisabled();
}
}
function _addGlobalAccess(address user) internal {
if (!s_globalAccessList[user]) {
s_globalAccessList[user] = true;
emit AccessAdded(user, "", msg.sender);
}
}
function _removeGlobalAccess(address user) internal {
if (s_globalAccessList[user]) {
s_globalAccessList[user] = false;
emit AccessRemoved(user, "", msg.sender);
}
}
function _addLocalAccess(address user, bytes memory data) internal {
if (!s_localAccessList[user][data]) {
s_localAccessList[user][data] = true;
emit AccessAdded(user, data, msg.sender);
}
}
function _removeLocalAccess(address user, bytes memory data) internal {
if (s_localAccessList[user][data]) {
s_localAccessList[user][data] = false;
emit AccessRemoved(user, data, msg.sender);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./WriteAccessController.sol";
import "../utils/EOAContext.sol";
/**
* @title ReadAccessController
* @notice Gives access to:
* - any externally owned account (note that offchain actors can always read
* any contract storage regardless of onchain access control measures, so this
* does not weaken the access control while improving usability)
* - accounts explicitly added to an access list
* @dev ReadAccessController is not suitable for access controlling writes
* since it grants any externally owned account access! See
* WriteAccessController for that.
*/
contract ReadAccessController is WriteAccessController, EOAContext {
/**
* @notice Returns the access of an address
* @param account The address to query
* @param data The calldata to query
*/
function hasAccess(
address account,
bytes memory data
)
public
view
virtual
override
returns (bool)
{
return super.hasAccess(account, data) || _isEOA(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/*
* @dev Provides information about the current execution context, specifically on if an account is an EOA on that chain.
* Different chains have different account abstractions, so this contract helps to switch behaviour between chains.
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract EOAContext {
function _isEOA(address account) internal view virtual returns (bool) {
return account == tx.origin; // solhint-disable-line avoid-tx-origin
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./WriteAccessController.sol";
import "../utils/EOAContext.sol";
/**
* @title PairReadAccessController
* @notice Extends WriteAccessController. Decodes the (asset, denomination) pair values of msg.data.
* @notice Gives access to:
* - any externally owned account (note that offchain actors can always read
* any contract storage regardless of onchain access control measures, so this
* does not weaken the access control while improving usability)
* - accounts explicitly added to an access list
* @dev PairReadAccessController is not suitable for access controlling writes
* since it grants any externally owned account access! See
* WriteAccessController for that.
*/
contract PairReadAccessController is WriteAccessController, EOAContext {
/**
* @notice Returns the access of an address to an asset/denomination pair
* @param account The address to query
* @param data The calldata to query
*/
function hasAccess(
address account,
bytes calldata data
)
public
view
virtual
override
returns (bool)
{
(
address asset,
address denomination
) = abi.decode(data[4:], (address, address));
bytes memory pairData = abi.encode(asset, denomination); // Check access to pair (TKN / ETH)
return super.hasAccess(account, pairData) || _isEOA(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./AggregatorV2V3Interface.sol";
interface AggregatorProxyInterface is AggregatorV2V3Interface {
function phaseAggregators(
uint16 phaseId
)
external
view
returns (
address
);
function phaseId()
external
view
returns (
uint16
);
function proposedAggregator()
external
view
returns (
address
);
function proposedGetRoundData(
uint80 roundId
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData()
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function aggregator()
external
view
returns (
address
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ConfirmedOwner.sol";
import "../interfaces/AggregatorProxyInterface.sol";
/**
* @title A trusted proxy for updating where current answers are read from
* @notice This contract provides a consistent address for the
* CurrentAnwerInterface but delegates where it reads from to the owner, who is
* trusted to update it.
*/
contract AggregatorProxy is AggregatorProxyInterface, ConfirmedOwner {
struct Phase {
uint16 id;
AggregatorProxyInterface aggregator;
}
AggregatorProxyInterface private s_proposedAggregator;
mapping(uint16 => AggregatorProxyInterface) private s_phaseAggregators;
Phase private s_currentPhase;
uint256 constant private PHASE_OFFSET = 64;
uint256 constant private PHASE_SIZE = 16;
uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1;
event AggregatorProposed(
address indexed current,
address indexed proposed
);
event AggregatorConfirmed(
address indexed previous,
address indexed latest
);
constructor(
address aggregatorAddress
)
ConfirmedOwner(msg.sender)
{
setAggregator(aggregatorAddress);
}
/**
* @notice Reads the current answer from aggregator delegated to.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (
int256 answer
)
{
return s_currentPhase.aggregator.latestAnswer();
}
/**
* @notice Reads the last updated height from aggregator delegated to.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (
uint256 updatedAt
)
{
return s_currentPhase.aggregator.latestTimestamp();
}
/**
* @notice get past rounds answers
* @param roundId the answer number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(
uint256 roundId
)
public
view
virtual
override
returns (
int256 answer
)
{
if (roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId);
AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId];
if (address(aggregator) == address(0)) return 0;
return aggregator.getAnswer(aggregatorRoundId);
}
/**
* @notice get block timestamp when an answer was last updated
* @param roundId the answer number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(
uint256 roundId
)
public
view
virtual
override
returns (
uint256 updatedAt
)
{
if (roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId);
AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId];
if (address(aggregator) == address(0)) return 0;
return aggregator.getTimestamp(aggregatorRoundId);
}
/**
* @notice get the latest completed round where the answer was updated. This
* ID includes the proxy's phase, to make sure round IDs increase even when
* switching to a newly deployed aggregator.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (
uint256 roundId
)
{
Phase memory phase = s_currentPhase; // cache storage reads
return addPhase(phase.id, uint64(phase.aggregator.latestRound()));
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param roundId the requested round ID as presented through the proxy, this
* is made up of the aggregator's round ID with the phase ID encoded in the
* two highest order bytes
* @return id is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function getRoundData(
uint80 roundId
)
public
view
virtual
override
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId);
(
id,
answer,
startedAt,
updatedAt,
answeredInRound
) = s_phaseAggregators[phaseId].getRoundData(aggregatorRoundId);
return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, phaseId);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @return id is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Phase memory current = s_currentPhase; // cache storage reads
(
id,
answer,
startedAt,
updatedAt,
answeredInRound
) = current.aggregator.latestRoundData();
return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, current.id);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @param roundId the round ID to retrieve the round data for
* @return id is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedGetRoundData(
uint80 roundId
)
external
view
virtual
override
hasProposal()
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return s_proposedAggregator.getRoundData(roundId);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @return id is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedLatestRoundData()
external
view
virtual
override
hasProposal()
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return s_proposedAggregator.latestRoundData();
}
/**
* @notice returns the current phase's aggregator address.
*/
function aggregator()
external
view
override
returns (
address
)
{
return address(s_currentPhase.aggregator);
}
/**
* @notice returns the current phase's ID.
*/
function phaseId()
external
view
override
returns (
uint16
)
{
return s_currentPhase.id;
}
/**
* @notice represents the number of decimals the aggregator responses represent.
*/
function decimals()
external
view
override
returns (
uint8
)
{
return s_currentPhase.aggregator.decimals();
}
/**
* @notice the version number representing the type of aggregator the proxy
* points to.
*/
function version()
external
view
override
returns (
uint256
)
{
return s_currentPhase.aggregator.version();
}
/**
* @notice returns the description of the aggregator the proxy points to.
*/
function description()
external
view
override
returns (
string memory
)
{
return s_currentPhase.aggregator.description();
}
/**
* @notice returns the current proposed aggregator
*/
function proposedAggregator()
external
view
override
returns (
address
)
{
return address(s_proposedAggregator);
}
/**
* @notice return a phase aggregator using the phaseId
*
* @param phaseId uint16
*/
function phaseAggregators(
uint16 phaseId
)
external
view
override
returns (
address
)
{
return address(s_phaseAggregators[phaseId]);
}
/**
* @notice Allows the owner to propose a new address for the aggregator
* @param aggregatorAddress The new address for the aggregator contract
*/
function proposeAggregator(
address aggregatorAddress
)
external
onlyOwner()
{
s_proposedAggregator = AggregatorProxyInterface(aggregatorAddress);
emit AggregatorProposed(address(s_currentPhase.aggregator), aggregatorAddress);
}
/**
* @notice Allows the owner to confirm and change the address
* to the proposed aggregator
* @dev Reverts if the given address doesn't match what was previously
* proposed
* @param aggregatorAddress The new address for the aggregator contract
*/
function confirmAggregator(
address aggregatorAddress
)
external
onlyOwner()
{
require(aggregatorAddress == address(s_proposedAggregator), "Invalid proposed aggregator");
address previousAggregator = address(s_currentPhase.aggregator);
delete s_proposedAggregator;
setAggregator(aggregatorAddress);
emit AggregatorConfirmed(previousAggregator, aggregatorAddress);
}
/*
* Internal
*/
function setAggregator(
address aggregatorAddress
)
internal
{
uint16 id = s_currentPhase.id + 1;
s_currentPhase = Phase(id, AggregatorProxyInterface(aggregatorAddress));
s_phaseAggregators[id] = AggregatorProxyInterface(aggregatorAddress);
}
function addPhase(
uint16 phase,
uint64 originalId
)
internal
pure
returns (
uint80
)
{
return uint80(uint256(phase) << PHASE_OFFSET | originalId);
}
function parseIds(
uint256 roundId
)
internal
pure
returns (
uint16,
uint64
)
{
uint16 phaseId = uint16(roundId >> PHASE_OFFSET);
uint64 aggregatorRoundId = uint64(roundId);
return (phaseId, aggregatorRoundId);
}
function addPhaseIds(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound,
uint16 phaseId
)
internal
pure
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
return (
addPhase(phaseId, uint64(roundId)),
answer,
startedAt,
updatedAt,
addPhase(phaseId, uint64(answeredInRound))
);
}
/*
* Modifiers
*/
modifier hasProposal() {
require(address(s_proposedAggregator) != address(0), "No proposed aggregator present");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title The ConfirmedOwner contract
* @notice A contract with helpers for basic contract ownership.
*/
contract ConfirmedOwner {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor(address newOwner) {
s_owner = newOwner;
}
/**
* @notice Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(
address to
)
external
onlyOwner()
{
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/**
* @notice Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @notice Get the current owner
*/
function owner()
public
view
returns (
address
)
{
return s_owner;
}
/**
* @notice Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == s_owner, "Only callable by owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@chainlink/contracts/src/v0.7/dev/AggregatorProxy.sol";
contract MockAggregatorProxy is AggregatorProxy {
constructor(
address aggregatorAddress
) AggregatorProxy(aggregatorAddress) {} // solhint-disable-line
}
|
retrieve the aggregator of an asset / denomination pair at a specific round id asset asset address denomination denomination address roundId the proxy round id/
|
function getRoundFeed(
address asset,
address denomination,
uint80 roundId
)
public
view
override
returns (
AggregatorV2V3Interface aggregator
)
{
uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId);
aggregator = _getPhaseFeed(asset, denomination, phaseId);
require(address(aggregator) != address(0), "Feed not found for round");
}
| 14,647,447
|
./partial_match/42/0xc3Fa8D75Ec3cb35f6cb7D640FcF1F0318f2cF9d7/sources/StakingRewards.sol
|
Register LP pair only once/
|
function registerGem(address gem) internal {
for (uint256 i = 0; i < registeredGems.length; i++) {
if (registeredGems[i] == gem) {
return;
}
}
registeredGems.push(gem);
}
| 8,846,312
|
/**
*Submitted for verification at Etherscan.io on 2021-02-06
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @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(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b <= a, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
// 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;
}
uint 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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint 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, uint 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,
uint 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,
uint 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.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 uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @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,
uint 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint 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/protocol/IStrategy.sol
/*
version 1.2.0
Changes
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- removed function assets(address _token) external view returns (bool);
- remove function deposit(uint), declared in IStrategyERC20
- add function setSlippage(uint _slippage);
- add function setDelta(uint _delta);
*/
interface IStrategy {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying asset (ETH or ERC20)
@dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying transferred from vault
*/
function totalDebt() external view returns (uint);
function performanceFee() external view returns (uint);
function slippage() external view returns (uint);
/*
@notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN
*/
function delta() external view returns (uint);
/*
@dev Flag to force exit in case normal exit fails
*/
function forceExit() external view returns (bool);
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setPerformanceFee(uint _fee) external;
function setSlippage(uint _slippage) external;
function setDelta(uint _delta) external;
function setForceExit(bool _forceExit) external;
/*
@notice Returns amount of underlying asset locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying asset is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Withdraw `_amount` underlying asset
@param amount Amount of underlying asset to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying asset from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external;
/*
@notice Exit from strategy
@dev Must transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/protocol/IStrategyETH.sol
interface IStrategyETH is IStrategy {
/*
@notice Deposit ETH
*/
function deposit() external payable;
}
// File: contracts/protocol/IController.sol
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: contracts/StrategyETH.sol
/*
version 1.2.0
*/
// used inside harvest
abstract contract StrategyETH is IStrategyETH {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
// Placeholder address to indicate that this is ETH strategy
address public constant override underlying =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// total amount of ETH transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public override performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// prevent slippage from deposit / withdraw
uint public override slippage = 100;
uint internal constant SLIPPAGE_MAX = 10000;
/*
Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN
*/
uint public override delta = 10050;
uint private constant DELTA_MIN = 10000;
// Force exit, in case normal exit fails
bool public override forceExit;
constructor(address _controller, address _vault) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
}
/*
@dev implement receive() external payable in child contract
@dev receive() should restrict msg.sender to prevent accidental ETH transfer
@dev vault and controller will never call receive()
*/
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin || msg.sender == controller || msg.sender == vault,
"!authorized"
);
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setPerformanceFee(uint _fee) external override onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setSlippage(uint _slippage) external override onlyAdmin {
require(_slippage <= SLIPPAGE_MAX, "slippage > max");
slippage = _slippage;
}
function setDelta(uint _delta) external override onlyAdmin {
require(_delta >= DELTA_MIN, "delta < min");
delta = _delta;
}
function setForceExit(bool _forceExit) external override onlyAdmin {
forceExit = _forceExit;
}
function _sendEthToVault(uint _amount) internal {
require(address(this).balance >= _amount, "ETH balance < amount");
(bool sent, ) = vault.call{value: _amount}("");
require(sent, "Send ETH failed");
}
function _increaseDebt(uint _ethAmount) private {
totalDebt = totalDebt.add(_ethAmount);
}
function _decreaseDebt(uint _ethAmount) private {
_sendEthToVault(_ethAmount);
if (_ethAmount > totalDebt) {
totalDebt = 0;
} else {
totalDebt -= _ethAmount;
}
}
function _totalAssets() internal view virtual returns (uint);
/*
@notice Returns amount of ETH locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _deposit() internal virtual;
/*
@notice Deposit ETH into this strategy
*/
function deposit() external payable override onlyAuthorized {
require(msg.value > 0, "deposit = 0");
_increaseDebt(msg.value);
_deposit();
}
/*
@notice Returns total shares owned by this contract for depositing ETH
into external Defi
*/
function _getTotalShares() internal view virtual returns (uint);
function _getShares(uint _ethAmount, uint _totalEth) internal view returns (uint) {
/*
calculate shares to withdraw
w = amount of ETH to withdraw
E = total redeemable ETH
s = shares to withdraw
P = total shares deposited into external liquidity pool
w / E = s / P
s = w / E * P
*/
if (_totalEth > 0) {
uint totalShares = _getTotalShares();
return _ethAmount.mul(totalShares) / _totalEth;
}
return 0;
}
function _withdraw(uint _shares) internal virtual;
/*
@notice Withdraw ETH to vault
@param _ethAmount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _ethAmount) external override onlyAuthorized {
require(_ethAmount > 0, "withdraw = 0");
uint totalEth = _totalAssets();
require(_ethAmount <= totalEth, "withdraw > total");
uint shares = _getShares(_ethAmount, totalEth);
if (shares > 0) {
_withdraw(shares);
}
// transfer ETH to vault
uint ethBal = address(this).balance;
if (ethBal > 0) {
_decreaseDebt(ethBal);
}
}
function _withdrawAll() internal {
uint totalShares = _getTotalShares();
if (totalShares > 0) {
_withdraw(totalShares);
}
// transfer ETH to vault
uint ethBal = address(this).balance;
if (ethBal > 0) {
_decreaseDebt(ethBal);
totalDebt = 0;
}
}
/*
@notice Withdraw all ETH to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@notice Sell any staking rewards for ETH and then deposit ETH
*/
function harvest() external virtual override;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external override onlyAuthorized {
uint totalEth = _totalAssets();
require(totalEth > totalDebt, "total ETH < debt");
uint profit = totalEth - totalDebt;
// protect against price manipulation
uint max = totalDebt.mul(delta) / DELTA_MIN;
if (totalEth <= max) {
/*
total ETH is within reasonable bounds, probaly no price
manipulation occured.
*/
/*
If we were to withdraw profit followed by deposit, this would
increase the total debt roughly by the profit.
Withdrawing consumes high gas, so here we omit it and
directly increase debt, as if withdraw and deposit were called.
*/
totalDebt = totalDebt.add(profit);
} else {
/*
Possible reasons for total ETH > max
1. total debt = 0
2. total ETH really did increase over max
3. price was manipulated
*/
uint shares = _getShares(profit, totalEth);
if (shares > 0) {
uint balBefore = address(this).balance;
_withdraw(shares);
uint balAfter = address(this).balance;
uint diff = balAfter.sub(balBefore);
if (diff > 0) {
_sendEthToVault(diff);
}
}
}
}
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/curve/LiquidityGaugeV2.sol
interface LiquidityGaugeV2 {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
function claim_rewards() external;
}
// File: contracts/interfaces/curve/Minter.sol
// https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy
interface Minter {
function mint(address) external;
}
// File: contracts/interfaces/curve/StableSwapSTETH.sol
interface StableSwapSTETH {
function get_virtual_price() external view returns (uint);
/*
0 ETH
1 STETH
*/
function balances(uint _index) external view returns (uint);
function add_liquidity(uint[2] memory amounts, uint min) external payable;
function remove_liquidity_one_coin(
uint _token_amount,
int128 i,
uint min_amount
) external;
}
// File: contracts/interfaces/lido/StETH.sol
interface StETH {
function submit(address) external payable returns (uint);
}
// File: contracts/strategies/StrategyStEth.sol
contract StrategyStEth is StrategyETH {
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Curve //
// liquidity provider token (Curve ETH/STETH)
address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E;
// StableSwapSTETH
address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022;
// LiquidityGaugeV2
address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28;
// Minter
address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// CRV
address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
// LIDO //
address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32;
constructor(address _controller, address _vault)
public
StrategyETH(_controller, _vault)
{
// These tokens are never held by this contract
// so the risk of them being stolen is minimal
IERC20(CRV).safeApprove(UNISWAP, uint(-1));
// Minted on Gauge deposit, withdraw and claim_rewards
// only this contract can spend on UNISWAP
IERC20(LDO).safeApprove(UNISWAP, uint(-1));
}
receive() external payable {
// Don't allow vault to accidentally send ETH
require(msg.sender != vault, "msg.sender == vault");
}
function _totalAssets() internal view override returns (uint) {
uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this));
uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price();
return shares.mul(pricePerShare) / 1e18;
}
function _getStEthDepositAmount(uint _ethBal) private view returns (uint) {
/*
Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1
E = amount of ETH
b0 = balance of ETH in Curve
b1 = balance of stETH in Curve
a0 = amount of ETH to deposit into Curve
a1 = amount of stETH to deposit into Curve
d = |b0 - b1|
if d >= E
if b0 >= b1
a0 = 0
a1 = E
else
a0 = E
a1 = 0
else
if b0 >= b1
# add d to balance Curve pool, plus half of remaining
a1 = d + (E - d) / 2 = (E + d) / 2
a0 = E - a1
else
a0 = (E + d) / 2
a1 = E - a0
*/
uint[2] memory balances;
balances[0] = StableSwapSTETH(POOL).balances(0);
balances[1] = StableSwapSTETH(POOL).balances(1);
uint diff;
if (balances[0] >= balances[1]) {
diff = balances[0] - balances[1];
} else {
diff = balances[1] - balances[0];
}
// a0 = ETH amount is ignored, recomputed after stEth is bought
// a1 = stETH amount
uint a1;
if (diff >= _ethBal) {
if (balances[0] >= balances[1]) {
a1 = _ethBal;
}
} else {
if (balances[0] >= balances[1]) {
a1 = (_ethBal.add(diff)) / 2;
} else {
a1 = _ethBal.sub((_ethBal.add(diff)) / 2);
}
}
// a0 is ignored, recomputed after stEth is bought
return a1;
}
/*
@notice Deposits ETH to LiquidityGaugeV2
*/
function _deposit() internal override {
uint bal = address(this).balance;
if (bal > 0) {
uint stEthAmount = _getStEthDepositAmount(bal);
if (stEthAmount > 0) {
StETH(ST_ETH).submit{value: stEthAmount}(address(this));
}
uint ethBal = address(this).balance;
uint stEthBal = IERC20(ST_ETH).balanceOf(address(this));
if (stEthBal > 0) {
// ST_ETH is proxy so don't allow infinite approval
IERC20(ST_ETH).safeApprove(POOL, stEthBal);
}
/*
shares = eth amount * 1e18 / price per share
*/
uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price();
uint shares = bal.mul(1e18).div(pricePerShare);
uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min);
}
// stake into LiquidityGaugeV2
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGaugeV2(GAUGE).deposit(lpBal);
}
}
function _getTotalShares() internal view override returns (uint) {
return LiquidityGaugeV2(GAUGE).balanceOf(address(this));
}
function _withdraw(uint _lpAmount) internal override {
// withdraw LP from LiquidityGaugeV2
LiquidityGaugeV2(GAUGE).withdraw(_lpAmount);
uint lpBal = IERC20(LP).balanceOf(address(this));
/*
eth amount = (shares * price per shares) / 1e18
*/
uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price();
uint ethAmount = lpBal.mul(pricePerShare) / 1e18;
uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min);
// Now we have ETH
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swapToEth(address _from, uint _amount) private {
// create dynamic array with 2 elements
address[] memory path = new address[](2);
path[0] = _from;
path[1] = WETH;
Uniswap(UNISWAP).swapExactTokensForETH(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards() private {
// claim LDO
LiquidityGaugeV2(GAUGE).claim_rewards();
// claim CRV
Minter(MINTER).mint(GAUGE);
// Infinity approval for Uniswap set inside constructor
uint ldoBal = IERC20(LDO).balanceOf(address(this));
if (ldoBal > 0) {
_swapToEth(LDO, ldoBal);
}
uint crvBal = IERC20(CRV).balanceOf(address(this));
if (crvBal > 0) {
_swapToEth(CRV, crvBal);
}
}
/*
@notice Claim CRV and deposit most premium token into Curve
*/
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
// treasury must be able to receive ETH
(bool sent, ) = treasury.call{value: fee}("");
require(sent, "Send ETH failed");
}
_deposit();
}
}
/*
@notice Exit strategy by harvesting CRV to underlying token and then
withdrawing all underlying to vault
@dev Must return all underlying token to vault
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
function sweep(address _token) external override onlyAdmin {
require(_token != GAUGE, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
|
claim LDO claim CRV Infinity approval for Uniswap set inside constructor
|
function _claimRewards() private {
LiquidityGaugeV2(GAUGE).claim_rewards();
Minter(MINTER).mint(GAUGE);
uint ldoBal = IERC20(LDO).balanceOf(address(this));
if (ldoBal > 0) {
_swapToEth(LDO, ldoBal);
}
uint crvBal = IERC20(CRV).balanceOf(address(this));
if (crvBal > 0) {
_swapToEth(CRV, crvBal);
}
}
| 2,460,622
|
/**
*Submitted for verification at Etherscan.io on 2022-01-08
*/
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/XBXPool.sol
/**
*Submitted for verification at BscScan.com on 2021-05-05
*/
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity 0.8.0;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
/**
* @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');
}
}
}
contract XBXPool is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The address of the smart chef factory
address public SMART_CHEF_FACTORY;
address public feeAddress;
// Whether a limit is set for users
bool public hasUserLimit;
// Whether it is initialized
bool public isInitialized;
// Accrued token per share
uint256 public accTokenPerShare;
// The block number when XBX mining ends.
uint256 public bonusEndBlock;
// The block number when XBX mining starts.
uint256 public startBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// XBX tokens created per block.
uint256 public rewardPerBlock;
// The precision factor
uint256 public PRECISION_FACTOR;
uint256 public lockStakeDate;
uint256 public lockWithdrawDate;
// The reward token
IERC20 public rewardToken;
// The staked token
IERC20 public stakedToken;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
}
event AdminTokenRecovery(address tokenRecovered, uint256 amount);
event Deposit(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event NewPoolLimit(uint256 poolLimitPerUser);
event RewardsStop(uint256 blockNumber);
event Withdraw(address indexed user, uint256 amount);
event Initialize(IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock,
uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin, uint256 _lockStakeDate,
uint256 _lockWithdrawDate, address _feeAddress);
event StopReward();
constructor() {
SMART_CHEF_FACTORY = msg.sender;
}
/*
* @notice Initialize the contract
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
* @param _rewardPerBlock: reward per block (in rewardToken)
* @param _startBlock: start block
* @param _bonusEndBlock: end block
* @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0)
* @param _admin: admin address with ownership
*/
function initialize(
IERC20 _stakedToken,
IERC20 _rewardToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock,
uint256 _poolLimitPerUser,
address _admin,
uint256 _lockStakeDate,
uint256 _lockWithdrawDate,
address _feeAddress
) external {
require(!isInitialized, 'Already initialized');
require(msg.sender == SMART_CHEF_FACTORY, 'Not factory');
require(_feeAddress != address(0), "_feeAddress: fee address is zero address");
require(_admin != address(0), "_admin: admin address is zero address");
// Make this contract initialized
isInitialized = true;
feeAddress = _feeAddress;
lockStakeDate = _lockStakeDate;
lockWithdrawDate = _lockWithdrawDate;
stakedToken = _stakedToken;
rewardToken = _rewardToken;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
if (_poolLimitPerUser > 0) {
hasUserLimit = true;
poolLimitPerUser = _poolLimitPerUser;
}
uint256 decimalsRewardToken = uint256(rewardToken.decimals());
require(decimalsRewardToken < 30, 'Must be inferior to 30');
PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken)));
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
// Transfer ownership to the admin address who becomes owner of the contract
transferOwnership(_admin);
emit Initialize(_stakedToken, _rewardToken, _rewardPerBlock, _startBlock, _bonusEndBlock, _poolLimitPerUser,
_admin, _lockStakeDate, _lockWithdrawDate, _feeAddress);
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in rewardToken)
*/
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(_amount.add(user.amount) <= poolLimitPerUser, 'User amount above limit');
}
if (lockStakeDate != 0 && _amount > 0) {
require(block.timestamp < lockStakeDate, 'XBX: stake locked');
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
if (pending > 0) {
uint256 fee = pending * 3 / 1000;
rewardToken.safeTransfer(address(msg.sender), pending - fee);
rewardToken.safeTransfer(address(feeAddress), fee);
}
}
if (_amount > 0) {
user.amount = user.amount.add(_amount);
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR);
emit Deposit(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, 'Amount to withdraw too high');
require(block.timestamp >= lockWithdrawDate, 'XBX: Withdraw was locked');
_updatePool();
uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
stakedToken.safeTransfer(address(msg.sender), _amount);
}
if (pending > 0) {
uint256 fee = pending * 3 / 1000;
rewardToken.safeTransfer(address(msg.sender), pending - fee);
rewardToken.safeTransfer(address(feeAddress), fee);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR);
emit Withdraw(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
if (amountToTransfer > 0) {
stakedToken.safeTransfer(address(msg.sender), amountToTransfer);
}
emit EmergencyWithdraw(msg.sender, user.amount);
}
/*
* @notice Stop rewards
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
rewardToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _amount);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakedToken), 'Cannot be staked token');
require(_tokenAddress != address(rewardToken), 'Cannot be reward token');
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/*
* @notice Stop rewards
* @dev Only callable by owner
*/
function stopReward() external onlyOwner {
bonusEndBlock = block.number;
emit StopReward();
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner {
if (_hasUserLimit) {
require(_poolLimitPerUser > poolLimitPerUser, 'New limit must be higher');
poolLimitPerUser = _poolLimitPerUser;
} else {
hasUserLimit = _hasUserLimit;
poolLimitPerUser = 0;
}
emit NewPoolLimit(poolLimitPerUser);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(block.number < startBlock, 'Pool has started');
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
/**
* @notice It allows the admin to update start and end blocks
* @dev This function is only callable by owner.
* @param _startBlock: the new start block
* @param _bonusEndBlock: the new end block
*/
function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner {
require(block.number < startBlock, 'Pool has started');
require(_startBlock < _bonusEndBlock, 'New startBlock must be lower than new endBlock');
require(block.number < _startBlock, 'New startBlock must be higher than current block');
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock);
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (block.number > lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 xbxReward = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare = accTokenPerShare.add(
xbxReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)
);
return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
} else {
return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
}
}
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply > 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 xbxReward = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(xbxReward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
}
lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from);
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock.sub(_from);
}
}
function getLockStakeDate() external view returns (uint256) {
return lockStakeDate;
}
function getLockWithdrawDate() external view returns (uint256) {
return lockWithdrawDate;
}
}
|
Deposit staked tokens and collect reward tokens (if any) _amount: amount to withdraw (in rewardToken)/
|
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(_amount.add(user.amount) <= poolLimitPerUser, 'User amount above limit');
}
if (lockStakeDate != 0 && _amount > 0) {
require(block.timestamp < lockStakeDate, 'XBX: stake locked');
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
if (pending > 0) {
uint256 fee = pending * 3 / 1000;
rewardToken.safeTransfer(address(msg.sender), pending - fee);
rewardToken.safeTransfer(address(feeAddress), fee);
}
}
if (_amount > 0) {
user.amount = user.amount.add(_amount);
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR);
emit Deposit(msg.sender, _amount);
}
| 15,097,927
|
./full_match/43113/0xA155ACe118d4D1581cC97967673aD66bEF0A9b9B/sources/_dincog_token.sol
|
Internal function to invoke `onApprovalReceived` on a target address The call is not executed if the target address is not a contract spender address The address which will spend the funds amount uint256 The amount of tokens to be spent data bytes Optional data to send along with the call return whether the call correctly returned the expected magic value/
|
function _checkAndCallApprove(
address spender,
uint256 amount,
bytes memory data
) internal virtual returns (bool) {
if (!isContract(spender)) {
return false;
}
bytes4 retval = IERC1363Spender(spender).onApprovalReceived(
_msgSender(),
amount,
data
);
return (retval == _ERC1363_APPROVED);
}
| 13,155,176
|
./partial_match/3/0xf5F1784aAE4a9875Bff819E97EB1B6ECEfFbcd17/sources/Election.sol
|
Delegate to `to` the weight of another valid voter's vote to delegate address/ Check that addr delegate has right to vote Forward the delegation if `to` also delegated. If delegate already voted, directly add to the number of votes Add sender weight to delegate as well in case delegate changes vote If delegate did not vote yet, add to weight.
|
function delegateVote(address to) public onlyVoter {
require(hasRole(VOTER_ROLE, to), "DOES_NOT_HAVE_VOTER_ROLE");
Voter storage sender = voters[_msgSender()];
require(!sender.voted, "Address has already voted");
while (voters[to].delegate != address(0) &&
voters[to].delegate != _msgSender()) {
to = voters[to].delegate;
}
require(to != _msgSender(), "Delegation can not be to self");
sender.delegate = to;
Voter storage delegate = voters[to];
if (delegate.voted) {
proposals[delegate.vote].voteCount += sender.weight;
delegate.weight += sender.weight;
delegate.weight += sender.weight;
}
}
| 5,204,854
|
./full_match/3/0x18523a12c70ae4Dc8Dc47da19fddB1197e3759d0/sources/browser/tests/2_mfi/1_MasterChef.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount);
userInfo[_pid][msg.sender].amount = userInfo[_pid][msg.sender].amount.sub(_amount);
userInfo[_pid][msg.sender].rewardDebt = userInfo[_pid][msg.sender].amount.mul(poolInfo[_pid].accMGPerShare).div(1e12);
poolInfo[_pid].lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 14,172,328
|
// SPDX-License-Identifier: MIT
/**
* ░█▄█░▄▀▄▒█▀▒▄▀▄░░░▒░░░▒██▀░█▀▄░█░▀█▀░█░▄▀▄░█▄░█░▄▀▀░░░█▄░█▒█▀░▀█▀
* ▒█▒█░▀▄▀░█▀░█▀█▒░░▀▀▒░░█▄▄▒█▄▀░█░▒█▒░█░▀▄▀░█▒▀█▒▄██▒░░█▒▀█░█▀░▒█▒
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Counters} from "@openzeppelin/contracts/utils/Counters.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import "./MintableEditions.sol";
contract MintableEditionsFactory is AccessControl {
bytes32 public constant ARTIST_ROLE = keccak256("ARTIST_ROLE");
using CountersUpgradeable for CountersUpgradeable.Counter;
// Counter for current contract id
CountersUpgradeable.Counter internal _counter;
// Address for implementation of Edition contract to clone
address private _implementation;
// Store for hash codes of editions contents: used to prevent re-issuing of the same content
mapping(bytes32 => bool) private _contents;
/**
* Initializes the factory with the address of the implementation contract template
*
* @param implementation Edition implementation contract to clone
*/
constructor(address implementation) {
_implementation = implementation;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(ARTIST_ROLE, msg.sender);
}
function setImplementation(address implementation) external onlyRole(DEFAULT_ADMIN_ROLE) {
_implementation = implementation;
}
/**
* Creates a new editions contract as a factory with a deterministic address, returning the address of the newly created contract.
* Important: None of these fields can be changed after calling this operation, with the sole exception of the contentUrl field which
* must refer to a content having the same hash.
*
* @param info name of editions, used in the title as "$name $tokenId/$size"
* @param size number of NFTs that can be minted from this contract: set to 0 for unbound
* @param price price for sale in wei
* @param royalties perpetual royalties paid to the creator upon token selling
* @param shares array of tuples listing the shareholders and their respective shares in bps (one per each shareholder)
* @param allowances array of tuples listing the allowed minters and their allowances
* @return the address of the editions contract created
*/
function create(
MintableEditions.Info memory info,
uint64 size,
uint256 price,
uint16 royalties,
MintableEditions.Shares[] memory shares,
MintableEditions.Allowance[] memory allowances
) external onlyRole(ARTIST_ROLE) returns (address) {
require(!_contents[info.contentHash], "Duplicated content");
_contents[info.contentHash] = true;
uint256 id = _counter.current();
address instance = Clones.cloneDeterministic(_implementation, bytes32(abi.encodePacked(id)));
MintableEditions(instance).initialize(msg.sender, info, size, price, royalties, shares, allowances);
emit CreatedEditions(id, msg.sender, shares, size, instance);
_counter.increment();
return instance;
}
/**
* Gets an editions contract given the unique identifier. Contract ids are zero-based.
*
* @param index zero-based index of editions contract to retrieve
* @return the editions contract
*/
function get(uint256 index) external view returns (MintableEditions) {
return MintableEditions(Clones.predictDeterministicAddress(_implementation, bytes32(abi.encodePacked(index)), address(this)));
}
/**
* @return the number of edition contracts created so far through this factory
*/
function instances() external view returns (uint256) {
return _counter.current();
}
/**
* Emitted when an edition is created reserving the corresponding token IDs.
*
* @param index the identifier of the newly created editions contract
* @param creator the editions' owner
* @param size the number of tokens this editions contract consists of
* @param contractAddress the address of the contract representing the editions
*/
event CreatedEditions(uint256 indexed index, address indexed creator, MintableEditions.Shares[] indexed shareholders, uint256 size, address contractAddress);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
/**
* ░█▄█░▄▀▄▒█▀▒▄▀▄░░░▒░░░▒██▀░█▀▄░█░▀█▀░█░▄▀▄░█▄░█░▄▀▀░░░█▄░█▒█▀░▀█▀
* ▒█▒█░▀▄▀░█▀░█▀█▒░░▀▀▒░░█▄▄▒█▄▀░█░▒█▒░█░▀▄▀░█▒▀█▒▄██▒░░█▒▀█░█▀░▒█▒
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {IERC2981Upgradeable, IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./EditionsMetadataHelper.sol";
import "./IMintableEditions.sol";
/**
* This contract allows dynamic NFT minting.
*
* Operations allow for selling publicly, partial or total giveaways, direct giveaways and rewardings.
*/
contract MintableEditions is ERC721Upgradeable, IERC2981Upgradeable, IMintableEditions, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
event PriceChanged(uint256 amount);
event EditionSold(uint256 price, address owner);
event SharesPaid(address to, uint256 amount);
struct Shares {
address payable holder;
uint16 bps;
}
struct Allowance {
address minter;
uint16 amount;
}
struct Info {
// name of editions, used in the title as "$name $tokenId/$size"
string name;
// symbol of the tokens minted by this contract
string symbol;
// description of token editions
string description;
// content URL of the token editions
string contentUrl;
// SHA256 of the token editions content in bytes32 format (0xHASH)
bytes32 contentHash;
// optional token editions content thumbnail URL, for animated content only
string thumbnailUrl;
}
// token id counter
CountersUpgradeable.Counter private counter;
// token description
string public description;
// token content URL
string public contentUrl;
// hash for the associated content
bytes32 public contentHash;
// token thumbnail URL, for animated content only
string public thumbnailUrl;
// the number of editions this contract can mint
uint64 public size;
// royalties ERC2981 in bps
uint16 public royalties;
// NFT rendering logic
EditionsMetadataHelper private immutable metadata;
// addresses allowed to mint editions
mapping(address => uint16) public allowedMinters;
// price for sale
uint256 public price;
// contract shareholders and shares information
address[] private shareholders;
mapping(address => uint16) public shares;
// shares withdrawals
uint256 private withdrawn;
mapping(address => uint256) private withdrawals;
constructor(EditionsMetadataHelper _metadata) initializer {
metadata = _metadata;
}
/**
* Creates a new edition and sets the only allowed minter to the address that creates/owns the edition: this can be re-assigned or updated later.
*
* @param _owner can authorize, mint, gets royalties and a dividend of sales, can update the content URL.
* @param _info token properties
* @param _size number of NFTs that can be minted from this contract: set to 0 for unbound
* @param _price sale price in wei
* @param _royalties perpetual royalties paid to the creator upon token selling
* @param _shares array of tuples listing the shareholders and their respective shares in bps (one per each shareholder)
* @param _allowances array of tuples listing the allowed minters and their allowances
*/
function initialize(
address _owner,
Info memory _info,
uint64 _size,
uint256 _price,
uint16 _royalties,
Shares[] memory _shares,
Allowance[] memory _allowances
) public initializer {
__ERC721_init(_info.name, _info.symbol);
__Ownable_init();
transferOwnership(_owner); // set ownership
description = _info.description;
require(bytes(_info.contentUrl).length > 0, "Empty content URL");
contentUrl = _info.contentUrl;
contentHash = _info.contentHash;
thumbnailUrl = _info.thumbnailUrl;
size = _size;
price = _price;
_setAllowances(_allowances);
counter.increment(); // token ids start at 1
require(_royalties < 10_000, "Royalties too high");
royalties = _royalties;
uint16 _totalShares;
for (uint256 i = 0; i < _shares.length; i++) {
_addPayee(_shares[i].holder, _shares[i].bps);
_totalShares += _shares[i].bps;
}
require(_totalShares < 10_000, "Shares too high");
_addPayee(payable(_owner), 10_000 - _totalShares);
}
function _addPayee(address payable _account, uint16 _shares) internal {
require(_account != address(0), "Shareholder is zero address");
require(_shares > 0 && _shares <= 10_000, "Shares are invalid");
require(shares[_account] == 0, "Shareholder already has shares");
shareholders.push(_account);
shares[_account] = _shares;
}
/**
* Returns the number of tokens minted so far
*/
function totalSupply() public view returns (uint256) {
return counter.current() - 1;
}
/**
* Basic ETH-based sales operation, performed at the given set price.
* This operation is open to everyone as soon as the salePrice is set to a non-zero value.
*/
function purchase() external payable returns (uint256) {
require(price > 0, "Not for sale");
require(msg.value == price, "Wrong price");
address[] memory toMint = new address[](1);
toMint[0] = msg.sender;
emit EditionSold(price, msg.sender);
return _mintEditions(toMint);
}
/**
* This operation sets the sale price, thus allowing anyone to acquire a token from this edition at the sale price via the purchase operation.
* Setting the sale price to 0 prevents purchase of the tokens which is then allowed only to permitted addresses.
*
* @param _wei if sale price is 0, no sale is allowed, otherwise the provided amount of WEI is needed to start the sale.
*/
function setPrice(uint256 _wei) external onlyOwner {
price = _wei;
emit PriceChanged(price);
}
/**
* Transfers all ETHs from the contract balance to the owner and shareholders.
*/
function shake() external {
for (uint i = 0; i < shareholders.length; i++) {
_withdraw(payable(shareholders[i]));
}
}
/**
* Transfers `withdrawable(msg.sender)` to the caller.
*/
function withdraw() external {
_withdraw(payable(msg.sender));
}
/**
* Returns how much the account can withdraw from this contract.
*/
function withdrawable(address payable _account) external view returns (uint256) {
uint256 _totalReceived = address(this).balance + withdrawn;
return (_totalReceived * shares[_account]) / 10_000 - withdrawals[_account];
}
/**
* INTERNAL: attempts to transfer part of the contract balance to the caller, provided the account is a shareholder and
* on the basis of its shares and previous withdrawals.
*
* @param _account the address of the shareholder to pay out
*/
function _withdraw(address payable _account) internal {
uint256 _amount = this.withdrawable(_account);
require(_amount != 0, "Account is not due payment");
withdrawals[_account] += _amount;
withdrawn += _amount;
AddressUpgradeable.sendValue(_account, _amount);
emit SharesPaid(_account, _amount);
}
/**
* INTERNAL: checks if the msg.sender is allowed to mint.
*/
function _isAllowedToMint() internal view returns (bool) {
return (owner() == msg.sender) || _isPublicAllowed() || (allowedMinters[msg.sender] > 0);
}
/**
* INTERNAL: checks if the ZeroAddress is allowed to mint.
*/
function _isPublicAllowed() internal view returns (bool) {
return (allowedMinters[address(0x0)] > 0);
}
/**
* If caller is listed as an allowed minter, mints one NFT for him.
*/
function mint() external override returns (uint256) {
require(_isAllowedToMint(), "Minting not allowed");
address[] memory toMint = new address[](1);
toMint[0] = msg.sender;
if (owner() != msg.sender && !_isPublicAllowed()) {
allowedMinters[msg.sender]--;
}
return _mintEditions(toMint);
}
/**
* Mints multiple tokens, one for each of the given list of addresses.
* Only the edition owner can use this operation and it is intended fo partial giveaways.
*
* @param recipients list of addresses to send the newly minted tokens to
*/
function mintAndTransfer(address[] memory recipients) external override returns (uint256) {
require(_isAllowedToMint(), "Minting not allowed");
if (owner() != msg.sender && !_isPublicAllowed()) {
require(allowedMinters[msg.sender] >= recipients.length, "Allowance exceeded");
allowedMinters[msg.sender] = allowedMinters[msg.sender] - uint16(recipients.length);
}
return _mintEditions(recipients);
}
/**
* Returns the owner of the collection of editions.
*/
function owner() public view override(OwnableUpgradeable, IMintableEditions) returns (address) {
return super.owner();
}
function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "New owner is the zero address");
shares[newOwner] = shares[newOwner] + shares[owner()];
shares[owner()] = 0;
_transferOwnership(newOwner);
}
function renounceOwnership() public override onlyOwner {
require(address(this).balance == 0 && price == 0, "Potential loss of funds");
_transferOwnership(address(0));
}
/**
* Allows the edition owner to set the amount of tokens (max 65535) an address is allowed to mint.
*
* If the ZeroAddress (address(0x0)) is set as a minter with an allowance greater than 0, anyone will be allowed
* to mint any amount of tokens, similarly to setApprovalForAll in the ERC721 spec.
* If the allowed amount is set to 0 then the address will NOT be allowed to mint.
*
* @param allowances tuples of (address, uint16) describing how many tokens an address is allowed to mint, 0 disables minting
*/
function setApprovedMinters(Allowance[] memory allowances) external onlyOwner {
_setAllowances(allowances);
}
function _setAllowances(Allowance[] memory allowances) internal {
for (uint i = 0; i < allowances.length; i++) {
allowedMinters[allowances[i].minter] = allowances[i].amount;
}
}
/**
* Allows for updates of edition urls by the owner of the edition.
* Only URLs can be updated (data-uris are supported), hashes cannot be updated.
*/
function updateEditionsURLs(string memory _contentUrl, string memory _thumbnailUrl) external onlyOwner {
require(bytes(_contentUrl).length > 0, "Empty content URL");
contentUrl = _contentUrl;
thumbnailUrl = _thumbnailUrl;
}
/**
* Returns the number of tokens still available for minting (uint64 when open edition)
*/
function mintable() public view override returns (uint256) {
// atEditionId is one-indexed hence the need to remove one here
return ((size == 0) ? type(uint64).max : size + 1) - counter.current();
}
/**
* User burn function for token id.
*
* @param tokenId token edition identifier to burn
*/
function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved");
_burn(tokenId);
}
/**
* Private function to mint without any access checks.
* Called by the public edition minting functions.
*/
function _mintEditions(address[] memory recipients) internal returns (uint256) {
require(uint64(mintable()) >= recipients.length, "Sold out");
for (uint i = 0; i < recipients.length; i++) {
_mint(recipients[i], counter.current());
counter.increment();
}
return counter.current();
}
/**
* Get URIs and hash for edition NFT
*
* @return contentUrl, contentHash
*/
function getURI() public view returns (string memory, bytes32, string memory) {
return (contentUrl, contentHash, thumbnailUrl);
}
/**
* Get URI for given token id
*
* @param tokenId token id to get uri for
* @return base64-encoded json metadata object
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Edition doesn't exist");
return metadata.createTokenURI(name(), description, contentUrl, thumbnailUrl, tokenId, size);
}
/**
* ERC2981 - Gets royalty information for token
*
* @param _value the sale price for this token
*/
function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) {
if (owner() == address(0x0)) {
return (owner(), 0);
}
return (owner(), (_value * royalties) / 10_000);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) {
return type(IERC2981Upgradeable).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
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 {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
/**
* ░█▄█░▄▀▄▒█▀▒▄▀▄░░░▒░░░▒██▀░█▀▄░█░▀█▀░█░▄▀▄░█▄░█░▄▀▀░░░█▄░█▒█▀░▀█▀
* ▒█▒█░▀▄▀░█▀░█▀█▒░░▀▀▒░░█▄▄▒█▄▀░█░▒█▒░█░▀▄▀░█▒▀█▒▄██▒░░█▒▀█░█▀░▒█▒
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {MetadataHelper} from "./MetadataHelper.sol";
/**
* Shared NFT logic for rendering metadata associated with editions
*/
contract EditionsMetadataHelper is MetadataHelper {
/**
* Generates edition metadata from storage information as base64-json blob
* Combines the media data and metadata
*
* @param name Name of NFT in metadata
* @param description Description of NFT in metadata
* @param contentUrl URL of content to render
* @param thumbnailUrl optional URL of a thumbnail to render, for animated content only
* @param tokenOfEdition unique identifier of a token edition
* @param size total count of editions
*/
function createTokenURI(string memory name, string memory description, string memory contentUrl, string memory thumbnailUrl, uint256 tokenOfEdition, uint256 size) external pure returns (string memory) {
string memory _tokenMediaData = tokenMediaData(contentUrl, thumbnailUrl, tokenOfEdition);
bytes memory json = createMetadata(name, description, _tokenMediaData, tokenOfEdition, size);
return encodeMetadata(json);
}
/**
* Function to create the metadata json string for the nft edition
*
* @param name Name of NFT in metadata
* @param description Description of NFT in metadata
* @param mediaData Data for media to include in json object
* @param tokenOfEdition Token ID for specific token
* @param size Size of entire edition to show
*/
function createMetadata(string memory name, string memory description, string memory mediaData, uint256 tokenOfEdition, uint256 size) public pure returns (bytes memory) {
bytes memory sizeText;
if (size > 0) {
sizeText = abi.encodePacked("/", numberToString(size));
}
return abi.encodePacked('{"name":"', name, " ", numberToString(tokenOfEdition), sizeText, '","description":"', description, '","',
mediaData, 'properties":{"number":', numberToString(tokenOfEdition), ',"name":"', name, '"}}');
}
/**
* Generates edition metadata from storage information as base64-json blob
* Combines the media data and metadata
*
* @param contentUrl URL of image to render for edition
* @param thumbnailUrl index of the content type to render for edition
* @param tokenOfEdition token identifier
*/
function tokenMediaData(string memory contentUrl, string memory thumbnailUrl, uint256 tokenOfEdition) public pure returns (string memory) {
if (bytes(thumbnailUrl).length == 0) {
return string(
abi.encodePacked(
'image":"', contentUrl, "?id=", numberToString(tokenOfEdition),'","'));
} else {
return string(
abi.encodePacked(
'image":"', thumbnailUrl, "?id=", numberToString(tokenOfEdition),'","animation_url":"', contentUrl, "?id=", numberToString(tokenOfEdition),'","'));
}
}
}
// SPDX-License-Identifier: MIT
/**
* ░█▄█░▄▀▄▒█▀▒▄▀▄░░░▒░░░▒██▀░█▀▄░█░▀█▀░█░▄▀▄░█▄░█░▄▀▀░░░█▄░█▒█▀░▀█▀
* ▒█▒█░▀▄▀░█▀░█▀█▒░░▀▀▒░░█▄▄▒█▄▀░█░▒█▒░█░▀▄▀░█▒▀█▒▄██▒░░█▒▀█░█▀░▒█▒
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
interface IMintableEditions {
/**
* Mints one token for the msg.sender.
*/
function mint() external returns (uint256);
/**
* Mints multiple tokens, one for each of the given addresses.
*
* @param to list of addresses to send the newly minted tokens to
*/
function mintAndTransfer(address[] memory to) external returns (uint256);
/**
* Returns the number of tokens still available for minting
*/
function mintable() external view returns (uint256);
/**
* Returns the owner of the editions contract.
*/
function owner() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
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
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
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
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal 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
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
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
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// SPDX-License-Identifier: MIT
/**
* ░█▄█░▄▀▄▒█▀▒▄▀▄░░░▒░░░▒██▀░█▀▄░█░▀█▀░█░▄▀▄░█▄░█░▄▀▀░░░█▄░█▒█▀░▀█▀
* ▒█▒█░▀▄▀░█▀░█▀█▒░░▀▀▒░░█▄▄▒█▄▀░█░▒█▒░█░▀▄▀░█▒▀█▒▄██▒░░█▒▀█░█▀░▒█▒
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import {Base64} from "base64-sol/base64.sol";
/**
* Shared utility functions for rendering on-chain metadata
*/
contract MetadataHelper {
/**
* @param unencoded bytes to base64-encode
*/
function base64Encode(bytes memory unencoded) public pure returns (string memory) {
return Base64.encode(unencoded);
}
/**
* Encodes the argument json bytes into base64-data uri format
*
* @param json raw json to base64 and turn into a data-uri
*/
function encodeMetadata(bytes memory json) public pure returns (string memory) {
return string(abi.encodePacked("data:application/json;base64,", base64Encode(json)));
}
/**
* Proxy to openzeppelin's toString function
*
* @param value number to return as a string
*/
function numberToString(uint256 value) public pure returns (string memory) {
return StringsUpgradeable.toString(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
|
Get URI for given token id tokenId token id to get uri for return base64-encoded json metadata object/
|
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Edition doesn't exist");
return metadata.createTokenURI(name(), description, contentUrl, thumbnailUrl, tokenId, size);
}
| 245,213
|
./partial_match/1/0x498FB942008780631c142FD5D930C08999e13DC1/sources/MINU.sol
|
once enabled, can never be turned off
|
function openTrading() external onlyOwner {
tradingActive = false;
swapEnabled = false;
lastLpBurnTime = block.timestamp;
}
| 3,579,384
|
./partial_match/42/0x3520b14d962818204912ee387b0871DA7902817d/sources/GOLDx.sol
|
Authorized function to set a new account to receive fee./
|
function setFeeRecipient(address _feeRecipient) external auth {
require(_feeRecipient != feeRecipient,
"setFeeRecipient: New fee recipient should be different!");
require(_feeRecipient != address(0),
"setFeeRecipient: New fee recipient should not be zero address!");
feeRecipient = _feeRecipient;
}
| 8,875,224
|
./partial_match/1/0xBCF85224fc0756B9Fa45aA7892530B47e10b6433/sources/src/v0.8/dev/DerivedPriceFeed.sol
|
https:docs.chain.link/docs/get-the-latest-price/getting-a-different-price-denomination
|
function getDerivedPrice() internal view returns (int256) {
(, int256 basePrice, , , ) = BASE.latestRoundData();
uint8 baseDecimals = BASE.decimals();
basePrice = scalePrice(basePrice, baseDecimals, DECIMALS);
(, int256 quotePrice, , , ) = QUOTE.latestRoundData();
uint8 quoteDecimals = QUOTE.decimals();
quotePrice = scalePrice(quotePrice, quoteDecimals, DECIMALS);
return (basePrice * int256(10**uint256(DECIMALS))) / quotePrice;
}
| 4,176,109
|
./partial_match/1/0xA53de764935d71968c7B5d311E6E76Ba22109a11/sources/DharmaTradeReserveV17ImplementationStaging.sol
|
Get the caller's balance prior to the transfer. Transfer the received tokens to the recipient. Ensure that sufficient tokens were returned to the user.
|
function _tradeEtherForTokenWithFeeOnTransferLegacy(
address tokenReceivedOrUSDCFlag,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 quotedTokenAmountAfterTransferFee,
uint256 deadline,
bool fromReserves
if (!fromReserves) {
uint256 priorRecipientBalanceOfReceivedToken = tokenReceived.balanceOf(
msg.sender
);
_transferToken(tokenReceived, msg.sender, quotedTokenAmount);
receivedAmountAfterTransferFee = tokenReceived.balanceOf(msg.sender).sub(
priorRecipientBalanceOfReceivedToken
);
require(
receivedAmountAfterTransferFee >= quotedTokenAmountAfterTransferFee,
"Received token amount after transfer fee is less than quoted amount."
);
}
| 9,400,990
|
./full_match/137/0x97c9242f3F81DdC89514780712E7358FF93836E7/sources/src/contracts/ContractOpenablePack.sol
|
Creates a pack with the stated contents.
|
function createPack(
uint256 packId,
Token[] calldata _contents,
uint256[] calldata _numOfRewardUnits,
uint128 _openStartTimestamp,
uint128 _amountDistributedPerOpen,
address _recipient
) external payable onlyRoleWithSwitch(minterRole) nonReentrant returns (uint256 packTotalSupply) {
require(_contents.length > 0 && _contents.length == _numOfRewardUnits.length, "!Len");
require(!created[packId], "!created");
if (!hasRole(assetRole, address(0))) {
for (uint256 i = 0; i < _contents.length; i += 1) {
_checkRole(assetRole, _contents[i].assetContract);
}
}
packTotalSupply = escrowPackContents(
_contents,
_numOfRewardUnits,
packId,
_amountDistributedPerOpen,
false
);
packInfo[packId].openStartTimestamp = _openStartTimestamp;
packInfo[packId].amountDistributedPerOpen = _amountDistributedPerOpen;
canUpdatePack[packId] = true;
created[packId] = true;
_mint(_recipient, packId, packTotalSupply, "");
emit PackCreated(packId, _recipient, packTotalSupply);
return packTotalSupply;
}
| 3,764,969
|
./full_match/1/0x007FEA2a31644F20b0fE18f69643890b6F878AA6/sources/src/bases/BondBaseSDA.sol
|
@inheritdoc IBondSDA
|
function marketPrice(uint256 id_) public view override returns (uint256) {
uint256 price = currentControlVariable(id_).mulDivUp(currentDebt(id_), markets[id_].scale);
return (price > markets[id_].minPrice) ? price : markets[id_].minPrice;
}
| 8,303,950
|
./partial_match/8453/0x4e30112363A4a047002E93FAf1ee99b30DeDA666/sources/contracts/zCloakSBT.sol
|
Used to set the unbind the ralation stored on chain/prettier-ignore revoke all related SBT
|
function unBinding(address bindingAddr, address bindedAddr) public payable {
if (_bindingDB[bindingAddr] != bindedAddr) {
revert BindingNotExist();
}
if (msg.sender == bindingAddr || msg.sender == bindedAddr) {
uint256[] memory revokeList = _bindedSBT[bindingAddr][bindedAddr];
for (uint i = 0; i < revokeList.length; i++){
if (_exists(revokeList[i])){
super._burn(revokeList[i]);
}
bytes32 publicInputHash = keccak256(abi.encodePacked(_tokenDB[revokeList[i]].publicInput));
delete _onlyTokenID[_tokenDB[revokeList[i]].digest][_tokenDB[revokeList[i]].attester][_tokenDB[revokeList[i]].programHash][publicInputHash][_tokenDB[revokeList[i]].ctype];
delete _certainSbtDB[_tokenDB[revokeList[i]].recipient][_tokenDB[revokeList[i]].attester][_tokenDB[revokeList[i]].programHash][publicInputHash][_tokenDB[revokeList[i]].ctype];
delete _tokenDB[revokeList[i]];
}
delete _bindedSBT[bindingAddr][bindedAddr];
if (revokeList.length != 0){
emit UserUnBindBurn(bindingAddr, revokeList);
}
emit UnBindingSuccess(bindingAddr, bindedAddr);
revert UnBindingLimited();
}
}
| 16,737,501
|
./full_match/97/0x22902bf8333c7BF3FF14cf835753612F70861f99/sources/project_/contracts/diamond/facets/DiamondCutFacet.sol
|
diamondCut((address,uint8,bytes4[])[],address,bytes)/
|
function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata) external override {
LibAccessControlEnumerable.checkRole(Constants.DEPLOYER_ROLE);
LibDiamond.diamondCut(_diamondCut, _init, _calldata);
}
| 3,290,569
|
// 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 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.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// 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 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: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./ModuleMapConsumer.sol";
import "../interfaces/IKernel.sol";
abstract contract Controlled is Initializable, ModuleMapConsumer {
// controller address => is a controller
mapping(address => bool) internal _controllers;
address[] public controllers;
function __Controlled_init(address[] memory controllers_, address moduleMap_)
public
initializer
{
for (uint256 i; i < controllers_.length; i++) {
_controllers[controllers_[i]] = true;
}
controllers = controllers_;
__ModuleMapConsumer_init(moduleMap_);
}
function addController(address controller) external onlyOwner {
_controllers[controller] = true;
bool added;
for (uint256 i; i < controllers.length; i++) {
if (controller == controllers[i]) {
added = true;
}
}
if (!added) {
controllers.push(controller);
}
}
modifier onlyOwner() {
require(
IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender),
"Controlled::onlyOwner: Caller is not owner"
);
_;
}
modifier onlyManager() {
require(
IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender),
"Controlled::onlyManager: Caller is not manager"
);
_;
}
modifier onlyController() {
require(
_controllers[msg.sender],
"Controlled::onlyController: Caller is not controller"
);
_;
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IModuleMap.sol";
abstract contract ModuleMapConsumer is Initializable {
IModuleMap public moduleMap;
function __ModuleMapConsumer_init(address moduleMap_) internal initializer {
moduleMap = IModuleMap(moduleMap_);
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./Controlled.sol";
import "./ModuleMapConsumer.sol";
import "../interfaces/IIntegrationMap.sol";
import "../interfaces/IUniswapFactory.sol";
import "../interfaces/IUniswapPositionManager.sol";
import "../interfaces/IUniswapSwapRouter.sol";
import "../interfaces/IUniswapTrader.sol";
import "../interfaces/IUniswapPool.sol";
import "../libraries/FullMath.sol";
/// @notice Integrates 0x Nodes to Uniswap v3
/// @notice tokenA/tokenB naming implies tokens are unsorted
/// @notice token0/token1 naming implies tokens are sorted
contract UniswapTrader is
Initializable,
ModuleMapConsumer,
Controlled,
IUniswapTrader
{
using SafeERC20Upgradeable for IERC20MetadataUpgradeable;
struct Pool {
uint24 feeNumerator;
uint24 slippageNumerator;
}
struct TokenPair {
address token0;
address token1;
}
uint24 private constant FEE_DENOMINATOR = 1_000_000;
uint24 private constant SLIPPAGE_DENOMINATOR = 1_000_000;
address private factoryAddress;
address private swapRouterAddress;
mapping(address => mapping(address => Pool[])) private pools;
mapping(address => mapping(address => Path)) private paths;
mapping(address => mapping(address => bool)) private isMultihopPair;
TokenPair[] private tokenPairs;
event UniswapPoolAdded(
address indexed token0,
address indexed token1,
uint24 fee,
uint24 slippageNumerator
);
event UniswapPoolSlippageNumeratorUpdated(
address indexed token0,
address indexed token1,
uint256 poolIndex,
uint24 slippageNumerator
);
event UniswapPairPrimaryPoolUpdated(
address indexed token0,
address indexed token1,
uint256 primaryPoolIndex
);
/// @param controllers_ The addresses of the controlling contracts
/// @param moduleMap_ Module Map address
/// @param factoryAddress_ The address of the Uniswap factory contract
/// @param swapRouterAddress_ The address of the Uniswap swap router contract
function initialize(
address[] memory controllers_,
address moduleMap_,
address factoryAddress_,
address swapRouterAddress_
) public initializer {
__Controlled_init(controllers_, moduleMap_);
__ModuleMapConsumer_init(moduleMap_);
factoryAddress = factoryAddress_;
swapRouterAddress = swapRouterAddress_;
}
/// @param tokenA The address of tokenA ERC20 contract
/// @param tokenB The address of tokenB ERC20 contract
/// @param feeNumerator The Uniswap pool fee numerator
/// @param slippageNumerator The value divided by the slippage denominator
/// to calculate the allowable slippage
/// positions is enabled for this pool
function addPool(
address tokenA,
address tokenB,
uint24 feeNumerator,
uint24 slippageNumerator
) external override onlyManager {
require(
IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap))
.getIsTokenAdded(tokenA),
"UniswapTrader::addPool: TokenA has not been added in the Integration Map"
);
require(
IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap))
.getIsTokenAdded(tokenB),
"UniswapTrader::addPool: TokenB has not been added in the Integration Map"
);
require(
slippageNumerator <= SLIPPAGE_DENOMINATOR,
"UniswapTrader::addPool: Slippage numerator cannot be greater than slippapge denominator"
);
require(
IUniswapFactory(factoryAddress).getPool(tokenA, tokenB, feeNumerator) !=
address(0),
"UniswapTrader::addPool: Pool does not exist"
);
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
bool poolAdded;
for (
uint256 poolIndex;
poolIndex < pools[token0][token1].length;
poolIndex++
) {
if (pools[token0][token1][poolIndex].feeNumerator == feeNumerator) {
poolAdded = true;
}
}
require(!poolAdded, "UniswapTrader::addPool: Pool has already been added");
Pool memory newPool;
newPool.feeNumerator = feeNumerator;
newPool.slippageNumerator = slippageNumerator;
pools[token0][token1].push(newPool);
bool tokenPairAdded;
for (uint256 pairIndex; pairIndex < tokenPairs.length; pairIndex++) {
if (
tokenPairs[pairIndex].token0 == token0 &&
tokenPairs[pairIndex].token1 == token1
) {
tokenPairAdded = true;
}
}
if (!tokenPairAdded) {
TokenPair memory newTokenPair;
newTokenPair.token0 = token0;
newTokenPair.token1 = token1;
tokenPairs.push(newTokenPair);
if (
IERC20MetadataUpgradeable(token0).allowance(
address(this),
moduleMap.getModuleAddress(Modules.YieldManager)
) == 0
) {
IERC20MetadataUpgradeable(token0).safeApprove(
moduleMap.getModuleAddress(Modules.YieldManager),
type(uint256).max
);
}
if (
IERC20MetadataUpgradeable(token1).allowance(
address(this),
moduleMap.getModuleAddress(Modules.YieldManager)
) == 0
) {
IERC20MetadataUpgradeable(token1).safeApprove(
moduleMap.getModuleAddress(Modules.YieldManager),
type(uint256).max
);
}
if (
IERC20MetadataUpgradeable(token0).allowance(
address(this),
swapRouterAddress
) == 0
) {
IERC20MetadataUpgradeable(token0).safeApprove(
swapRouterAddress,
type(uint256).max
);
}
if (
IERC20MetadataUpgradeable(token1).allowance(
address(this),
swapRouterAddress
) == 0
) {
IERC20MetadataUpgradeable(token1).safeApprove(
swapRouterAddress,
type(uint256).max
);
}
}
emit UniswapPoolAdded(token0, token1, feeNumerator, slippageNumerator);
}
/// @param tokenA The address of tokenA of the pool
/// @param tokenB The address of tokenB of the pool
/// @param poolIndex The index of the pool for the specified token pair
/// @param slippageNumerator The new slippage numerator to update the pool
function updatePoolSlippageNumerator(
address tokenA,
address tokenB,
uint256 poolIndex,
uint24 slippageNumerator
) external override onlyManager {
require(
slippageNumerator <= SLIPPAGE_DENOMINATOR,
"UniswapTrader:updatePoolSlippageNumerator: Slippage numerator must not be greater than slippage denominator"
);
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
require(
pools[token0][token1][poolIndex].slippageNumerator != slippageNumerator,
"UniswapTrader:updatePoolSlippageNumerator: Slippage numerator must be updated to a new number"
);
require(
pools[token0][token1].length > poolIndex,
"UniswapTrader:updatePoolSlippageNumerator: Pool does not exist"
);
pools[token0][token1][poolIndex].slippageNumerator = slippageNumerator;
emit UniswapPoolSlippageNumeratorUpdated(
token0,
token1,
poolIndex,
slippageNumerator
);
}
/// @notice Updates which Uniswap pool to use as the default pool
/// @notice when swapping between token0 and token1
/// @param tokenA The address of tokenA of the pool
/// @param tokenB The address of tokenB of the pool
/// @param primaryPoolIndex The index of the Uniswap pool to make the new primary pool
function updatePairPrimaryPool(
address tokenA,
address tokenB,
uint256 primaryPoolIndex
) external override onlyManager {
require(
primaryPoolIndex != 0,
"UniswapTrader::updatePairPrimaryPool: Specified index is already the primary pool"
);
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
require(
primaryPoolIndex < pools[token0][token1].length,
"UniswapTrader::updatePairPrimaryPool: Specified pool index does not exist"
);
uint24 newPrimaryPoolFeeNumerator = pools[token0][token1][primaryPoolIndex]
.feeNumerator;
uint24 newPrimaryPoolSlippageNumerator = pools[token0][token1][
primaryPoolIndex
].slippageNumerator;
pools[token0][token1][primaryPoolIndex].feeNumerator = pools[token0][
token1
][0].feeNumerator;
pools[token0][token1][primaryPoolIndex].slippageNumerator = pools[token0][
token1
][0].slippageNumerator;
pools[token0][token1][0].feeNumerator = newPrimaryPoolFeeNumerator;
pools[token0][token1][0]
.slippageNumerator = newPrimaryPoolSlippageNumerator;
emit UniswapPairPrimaryPoolUpdated(token0, token1, primaryPoolIndex);
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param recipient The address to receive the tokens
/// @param amountIn The exact amount of the input to swap
/// @return tradeSuccess Indicates whether the trade succeeded
function swapExactInput(
address tokenIn,
address tokenOut,
address recipient,
uint256 amountIn
) external override onlyController returns (bool tradeSuccess) {
IERC20MetadataUpgradeable tokenInErc20 = IERC20MetadataUpgradeable(tokenIn);
if (isMultihopPair[tokenIn][tokenOut]) {
Path memory path = getPathFor(tokenIn, tokenOut);
IUniswapSwapRouter.ExactInputParams memory params = IUniswapSwapRouter
.ExactInputParams({
path: abi.encodePacked(
path.tokenIn,
path.firstPoolFee,
path.tokenInTokenOut,
path.secondPoolFee,
path.tokenOut
),
recipient: recipient,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0
});
// Executes the swap.
try IUniswapSwapRouter(swapRouterAddress).exactInput(params) {
tradeSuccess = true;
} catch {
tradeSuccess = false;
tokenInErc20.safeTransfer(
recipient,
tokenInErc20.balanceOf(address(this))
);
}
return tradeSuccess;
}
(address token0, address token1) = getTokensSorted(tokenIn, tokenOut);
require(
pools[token0][token1].length > 0,
"UniswapTrader::swapExactInput: Pool has not been added"
);
require(
tokenInErc20.balanceOf(address(this)) >= amountIn,
"UniswapTrader::swapExactInput: Balance is less than trade amount"
);
uint256 amountOutMinimum = getAmountOutMinimum(tokenIn, tokenOut, amountIn);
IUniswapSwapRouter.ExactInputSingleParams memory exactInputSingleParams;
exactInputSingleParams.tokenIn = tokenIn;
exactInputSingleParams.tokenOut = tokenOut;
exactInputSingleParams.fee = pools[token0][token1][0].feeNumerator;
exactInputSingleParams.recipient = recipient;
exactInputSingleParams.deadline = block.timestamp;
exactInputSingleParams.amountIn = amountIn;
exactInputSingleParams.amountOutMinimum = amountOutMinimum;
exactInputSingleParams.sqrtPriceLimitX96 = 0;
try
IUniswapSwapRouter(swapRouterAddress).exactInputSingle(
exactInputSingleParams
)
{
tradeSuccess = true;
} catch {
tradeSuccess = false;
tokenInErc20.safeTransfer(
recipient,
tokenInErc20.balanceOf(address(this))
);
}
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param recipient The address to receive the tokens
/// @param amountOut The exact amount of the output token to receive
/// @return tradeSuccess Indicates whether the trade succeeded
function swapExactOutput(
address tokenIn,
address tokenOut,
address recipient,
uint256 amountOut
) external override onlyController returns (bool tradeSuccess) {
IERC20MetadataUpgradeable tokenInErc20 = IERC20MetadataUpgradeable(tokenIn);
if (isMultihopPair[tokenIn][tokenOut]) {
Path memory path = getPathFor(tokenIn, tokenOut);
IUniswapSwapRouter.ExactOutputParams memory params = IUniswapSwapRouter
.ExactOutputParams({
path: abi.encodePacked(
path.tokenIn,
path.firstPoolFee,
path.tokenInTokenOut,
path.secondPoolFee,
path.tokenOut
),
recipient: recipient,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: 0
});
// Executes the swap.
try IUniswapSwapRouter(swapRouterAddress).exactOutput(params) {
tradeSuccess = true;
} catch {
tradeSuccess = false;
tokenInErc20.safeTransfer(
recipient,
tokenInErc20.balanceOf(address(this))
);
}
return tradeSuccess;
}
(address token0, address token1) = getTokensSorted(tokenIn, tokenOut);
require(
pools[token0][token1][0].feeNumerator > 0,
"UniswapTrader::swapExactOutput: Pool has not been added"
);
uint256 amountInMaximum = getAmountInMaximum(tokenIn, tokenOut, amountOut);
require(
tokenInErc20.balanceOf(address(this)) >= amountInMaximum,
"UniswapTrader::swapExactOutput: Balance is less than trade amount"
);
IUniswapSwapRouter.ExactOutputSingleParams memory exactOutputSingleParams;
exactOutputSingleParams.tokenIn = tokenIn;
exactOutputSingleParams.tokenOut = tokenOut;
exactOutputSingleParams.fee = pools[token0][token1][0].feeNumerator;
exactOutputSingleParams.recipient = recipient;
exactOutputSingleParams.deadline = block.timestamp;
exactOutputSingleParams.amountOut = amountOut;
exactOutputSingleParams.amountInMaximum = amountInMaximum;
exactOutputSingleParams.sqrtPriceLimitX96 = 0;
try
IUniswapSwapRouter(swapRouterAddress).exactOutputSingle(
exactOutputSingleParams
)
{
tradeSuccess = true;
} catch {
tradeSuccess = false;
tokenInErc20.safeTransfer(
recipient,
tokenInErc20.balanceOf(address(this))
);
}
}
/// @param tokenA The address of tokenA ERC20 contract
/// @param tokenB The address of tokenB ERC20 contract
/// @return pool The pool address
function getPoolAddress(address tokenA, address tokenB)
public
view
override
returns (address pool)
{
uint24 feeNumerator = getPoolFeeNumerator(tokenA, tokenB, 0);
pool = IUniswapFactory(factoryAddress).getPool(
tokenA,
tokenB,
feeNumerator
);
}
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
function getSqrtPriceX96(address tokenA, address tokenB)
public
view
returns (uint256)
{
(uint160 sqrtPriceX96, , , , , , ) = IUniswapPool(
getPoolAddress(tokenA, tokenB)
).slot0();
return uint256(sqrtPriceX96);
}
function getPathFor(address tokenIn, address tokenOut)
public
view
override
returns (Path memory)
{
require(
isMultihopPair[tokenIn][tokenOut],
"There is an existing Pool for this pair"
);
return paths[tokenIn][tokenOut];
}
function setPathFor(
address tokenIn,
address tokenOut,
uint256 firstPoolFee,
address tokenInTokenOut,
uint256 secondPoolFee
) public override onlyManager {
paths[tokenIn][tokenOut] = Path(
tokenIn,
firstPoolFee,
tokenInTokenOut,
secondPoolFee,
tokenOut
);
isMultihopPair[tokenIn][tokenOut] = true;
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountIn The exact amount of the input to swap
/// @return amountOutMinimum The minimum amount of tokenOut to receive, factoring in allowable slippage
function getAmountOutMinimum(
address tokenIn,
address tokenOut,
uint256 amountIn
) public view returns (uint256 amountOutMinimum) {
uint256 estimatedAmountOut = getEstimatedTokenOut(
tokenIn,
tokenOut,
amountIn
);
uint24 poolSlippageNumerator = getPoolSlippageNumerator(
tokenIn,
tokenOut,
0
);
amountOutMinimum =
(estimatedAmountOut * (SLIPPAGE_DENOMINATOR - poolSlippageNumerator)) /
SLIPPAGE_DENOMINATOR;
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountOut The exact amount of token being swapped for
/// @return amountInMaximum The maximum amount of tokenIn to spend, factoring in allowable slippage
function getAmountInMaximum(
address tokenIn,
address tokenOut,
uint256 amountOut
) public view override returns (uint256 amountInMaximum) {
uint256 estimatedAmountIn = getEstimatedTokenIn(
tokenIn,
tokenOut,
amountOut
);
uint24 poolSlippageNumerator = getPoolSlippageNumerator(
tokenIn,
tokenOut,
0
);
amountInMaximum =
(estimatedAmountIn * (SLIPPAGE_DENOMINATOR + poolSlippageNumerator)) /
SLIPPAGE_DENOMINATOR;
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountIn The exact amount of the input to swap
/// @return amountOut The estimated amount of tokenOut to receive
function getEstimatedTokenOut(
address tokenIn,
address tokenOut,
uint256 amountIn
) public view override returns (uint256 amountOut) {
if (isMultihopPair[tokenIn][tokenOut]) {
Path memory path = getPathFor(tokenIn, tokenOut);
uint256 amountOutTemp = getEstimatedTokenOut(
path.tokenIn,
path.tokenInTokenOut,
amountIn
);
return
getEstimatedTokenOut(
path.tokenInTokenOut,
path.tokenOut,
amountOutTemp
);
}
uint24 feeNumerator = getPoolFeeNumerator(tokenIn, tokenOut, 0);
uint256 sqrtPriceX96 = getSqrtPriceX96(tokenIn, tokenOut);
// FullMath is used to allow intermediate calculation values of up to 2^512
if (tokenIn < tokenOut) {
amountOut =
(FullMath.mulDiv(
FullMath.mulDiv(amountIn, sqrtPriceX96, 2**96),
sqrtPriceX96,
2**96
) * (FEE_DENOMINATOR - feeNumerator)) /
FEE_DENOMINATOR;
} else {
amountOut =
(FullMath.mulDiv(
FullMath.mulDiv(amountIn, 2**96, sqrtPriceX96),
2**96,
sqrtPriceX96
) * (FEE_DENOMINATOR - feeNumerator)) /
FEE_DENOMINATOR;
}
}
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountOut The exact amount of the output token to swap for
/// @return amountIn The estimated amount of tokenIn to spend
function getEstimatedTokenIn(
address tokenIn,
address tokenOut,
uint256 amountOut
) public view returns (uint256 amountIn) {
if (isMultihopPair[tokenIn][tokenOut]) {
Path memory path = getPathFor(tokenIn, tokenOut);
uint256 amountInTemp = getEstimatedTokenIn(
path.tokenInTokenOut,
path.tokenOut,
amountOut
);
return
getEstimatedTokenIn(path.tokenIn, path.tokenInTokenOut, amountInTemp);
}
uint24 feeNumerator = getPoolFeeNumerator(tokenIn, tokenOut, 0);
uint256 sqrtPriceX96 = getSqrtPriceX96(tokenIn, tokenOut);
// FullMath is used to allow intermediate calculation values of up to 2^512
if (tokenIn < tokenOut) {
amountIn =
(FullMath.mulDiv(
FullMath.mulDiv(amountOut, 2**96, sqrtPriceX96),
2**96,
sqrtPriceX96
) * (FEE_DENOMINATOR - feeNumerator)) /
FEE_DENOMINATOR;
} else {
amountIn =
(FullMath.mulDiv(
FullMath.mulDiv(amountOut, sqrtPriceX96, 2**96),
sqrtPriceX96,
2**96
) * (FEE_DENOMINATOR - feeNumerator)) /
FEE_DENOMINATOR;
}
}
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @param poolId The index of the pool in the pools mapping
/// @return feeNumerator The numerator that gets divided by the fee denominator
function getPoolFeeNumerator(
address tokenA,
address tokenB,
uint256 poolId
) public view override returns (uint24 feeNumerator) {
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
require(
poolId < pools[token0][token1].length,
"UniswapTrader::getPoolFeeNumerator: Pool ID does not exist"
);
feeNumerator = pools[token0][token1][poolId].feeNumerator;
}
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @param poolId The index of the pool in the pools mapping
/// @return slippageNumerator The numerator that gets divided by the slippage denominator
function getPoolSlippageNumerator(
address tokenA,
address tokenB,
uint256 poolId
) public view returns (uint24 slippageNumerator) {
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
return pools[token0][token1][poolId].slippageNumerator;
}
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @return token0 The address of the sorted token0
/// @return token1 The address of the sorted token1
function getTokensSorted(address tokenA, address tokenB)
public
pure
override
returns (address token0, address token1)
{
if (tokenA < tokenB) {
token0 = tokenA;
token1 = tokenB;
} else {
token0 = tokenB;
token1 = tokenA;
}
}
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @param amountA The amount of tokenA
/// @param amountB The amount of tokenB
/// @return token0 The address of sorted token0
/// @return token1 The address of sorted token1
/// @return amount0 The amount of sorted token0
/// @return amount1 The amount of sorted token1
function getTokensAndAmountsSorted(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
)
public
pure
returns (
address token0,
address token1,
uint256 amount0,
uint256 amount1
)
{
if (tokenA < tokenB) {
token0 = tokenA;
token1 = tokenB;
amount0 = amountA;
amount1 = amountB;
} else {
token0 = tokenB;
token1 = tokenA;
amount0 = amountB;
amount1 = amountA;
}
}
/// @return The denominator used to calculate the pool fee percentage
function getFeeDenominator() external pure returns (uint24) {
return FEE_DENOMINATOR;
}
/// @return The denominator used to calculate the allowable slippage percentage
function getSlippageDenominator() external pure returns (uint24) {
return SLIPPAGE_DENOMINATOR;
}
/// @return The number of token pairs configured
function getTokenPairsLength() external view override returns (uint256) {
return tokenPairs.length;
}
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @return The quantity of pools configured for the specified token pair
function getTokenPairPoolsLength(address tokenA, address tokenB)
external
view
override
returns (uint256)
{
(address token0, address token1) = getTokensSorted(tokenA, tokenB);
return pools[token0][token1].length;
}
/// @param tokenPairIndex The index of the token pair
/// @return The address of token0
/// @return The address of token1
function getTokenPair(uint256 tokenPairIndex)
external
view
returns (address, address)
{
require(
tokenPairIndex < tokenPairs.length,
"UniswapTrader::getTokenPair: Token pair does not exist"
);
return (
tokenPairs[tokenPairIndex].token0,
tokenPairs[tokenPairIndex].token1
);
}
/// @param token0 The address of token0 of the pool
/// @param token1 The address of token1 of the pool
/// @param poolIndex The index of the pool
/// @return The pool fee numerator
/// @return The pool slippage numerator
function getPool(
address token0,
address token1,
uint256 poolIndex
) external view returns (uint24, uint24) {
require(
poolIndex < pools[token0][token1].length,
"UniswapTrader:getPool: Pool does not exist"
);
return (
pools[token0][token1][poolIndex].feeNumerator,
pools[token0][token1][poolIndex].slippageNumerator
);
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IIntegrationMap {
struct Integration {
bool added;
string name;
}
struct Token {
uint256 id;
bool added;
bool acceptingDeposits;
bool acceptingWithdrawals;
uint256 biosRewardWeight;
uint256 reserveRatioNumerator;
}
/// @param contractAddress The address of the integration contract
/// @param name The name of the protocol being integrated to
function addIntegration(address contractAddress, string memory name) external;
/// @param tokenAddress The address of the ERC20 token contract
/// @param acceptingDeposits Whether token deposits are enabled
/// @param acceptingWithdrawals Whether token withdrawals are enabled
/// @param biosRewardWeight Token weight for BIOS rewards
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function addToken(
address tokenAddress,
bool acceptingDeposits,
bool acceptingWithdrawals,
uint256 biosRewardWeight,
uint256 reserveRatioNumerator
) external;
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenDeposits(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenDeposits(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenWithdrawals(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenWithdrawals(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
/// @param rewardWeight The updated token BIOS reward weight
function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight)
external;
/// @param tokenAddress the address of the token ERC20 contract
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function updateTokenReserveRatioNumerator(
address tokenAddress,
uint256 reserveRatioNumerator
) external;
/// @param integrationId The ID of the integration
/// @return The address of the integration contract
function getIntegrationAddress(uint256 integrationId)
external
view
returns (address);
/// @param integrationAddress The address of the integration contract
/// @return The name of the of the protocol being integrated to
function getIntegrationName(address integrationAddress)
external
view
returns (string memory);
/// @return The address of the WETH token
function getWethTokenAddress() external view returns (address);
/// @return The address of the BIOS token
function getBiosTokenAddress() external view returns (address);
/// @param tokenId The ID of the token
/// @return The address of the token ERC20 contract
function getTokenAddress(uint256 tokenId) external view returns (address);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The index of the token in the tokens array
function getTokenId(address tokenAddress) external view returns (uint256);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The token BIOS reward weight
function getTokenBiosRewardWeight(address tokenAddress)
external
view
returns (uint256);
/// @return rewardWeightSum reward weight of depositable tokens
function getBiosRewardWeightSum()
external
view
returns (uint256 rewardWeightSum);
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether depositing this token is currently enabled
function getTokenAcceptingDeposits(address tokenAddress)
external
view
returns (bool);
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether withdrawing this token is currently enabled
function getTokenAcceptingWithdrawals(address tokenAddress)
external
view
returns (bool);
// @param tokenAddress The address of the token ERC20 contract
// @return bool indicating whether the token has been added
function getIsTokenAdded(address tokenAddress) external view returns (bool);
// @param integrationAddress The address of the integration contract
// @return bool indicating whether the integration has been added
function getIsIntegrationAdded(address tokenAddress)
external
view
returns (bool);
/// @notice get the length of supported tokens
/// @return The quantity of tokens added
function getTokenAddressesLength() external view returns (uint256);
/// @notice get the length of supported integrations
/// @return The quantity of integrations added
function getIntegrationAddressesLength() external view returns (uint256);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The value that gets divided by the reserve ratio denominator
function getTokenReserveRatioNumerator(address tokenAddress)
external
view
returns (uint256);
/// @return The token reserve ratio denominator
function getReserveRatioDenominator() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IKernel {
/// @param account The address of the account to check if they are a manager
/// @return Bool indicating whether the account is a manger
function isManager(address account) external view returns (bool);
/// @param account The address of the account to check if they are an owner
/// @return Bool indicating whether the account is an owner
function isOwner(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
enum Modules {
Kernel, // 0
UserPositions, // 1
YieldManager, // 2
IntegrationMap, // 3
BiosRewards, // 4
EtherRewards, // 5
SushiSwapTrader, // 6
UniswapTrader, // 7
StrategyMap, // 8
StrategyManager // 9
}
interface IModuleMap {
function getModuleAddress(Modules key) external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IUniswapFactory {
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IUniswapPool {
/// @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
);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IUniswapPositionManager {
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IUniswapSwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
function exactInput(ExactInputParams calldata params)
external
returns (uint256 amountOut);
function exactOutput(ExactOutputParams calldata params)
external
returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IUniswapTrader {
struct Path {
address tokenOut;
uint256 firstPoolFee;
address tokenInTokenOut;
uint256 secondPoolFee;
address tokenIn;
}
/// @param tokenA The address of tokenA ERC20 contract
/// @param tokenB The address of tokenB ERC20 contract
/// @param fee The Uniswap pool fee
/// @param slippageNumerator The value divided by the slippage denominator
/// to calculate the allowable slippage
function addPool(
address tokenA,
address tokenB,
uint24 fee,
uint24 slippageNumerator
) external;
/// @param tokenA The address of tokenA of the pool
/// @param tokenB The address of tokenB of the pool
/// @param poolIndex The index of the pool for the specified token pair
/// @param slippageNumerator The new slippage numerator to update the pool
function updatePoolSlippageNumerator(
address tokenA,
address tokenB,
uint256 poolIndex,
uint24 slippageNumerator
) external;
/// @notice Changes which Uniswap pool to use as the default pool
/// @notice when swapping between token0 and token1
/// @param tokenA The address of tokenA of the pool
/// @param tokenB The address of tokenB of the pool
/// @param primaryPoolIndex The index of the Uniswap pool to make the new primary pool
function updatePairPrimaryPool(
address tokenA,
address tokenB,
uint256 primaryPoolIndex
) external;
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param recipient The address to receive the tokens
/// @param amountIn The exact amount of the input to swap
/// @return tradeSuccess Indicates whether the trade succeeded
function swapExactInput(
address tokenIn,
address tokenOut,
address recipient,
uint256 amountIn
) external returns (bool tradeSuccess);
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param recipient The address to receive the tokens
/// @param amountOut The exact amount of the output token to receive
/// @return tradeSuccess Indicates whether the trade succeeded
function swapExactOutput(
address tokenIn,
address tokenOut,
address recipient,
uint256 amountOut
) external returns (bool tradeSuccess);
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountOut The exact amount of token being swapped for
/// @return amountInMaximum The maximum amount of tokenIn to spend, factoring in allowable slippage
function getAmountInMaximum(
address tokenIn,
address tokenOut,
uint256 amountOut
) external view returns (uint256 amountInMaximum);
/// @param tokenIn The address of the input token
/// @param tokenOut The address of the output token
/// @param amountIn The exact amount of the input to swap
/// @return amountOut The estimated amount of tokenOut to receive
function getEstimatedTokenOut(
address tokenIn,
address tokenOut,
uint256 amountIn
) external view returns (uint256 amountOut);
function getPathFor(address tokenOut, address tokenIn)
external
view
returns (Path memory);
function setPathFor(
address tokenOut,
address tokenIn,
uint256 firstPoolFee,
address tokenInTokenOut,
uint256 secondPoolFee
) external;
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @return token0 The address of the sorted token0
/// @return token1 The address of the sorted token1
function getTokensSorted(address tokenA, address tokenB)
external
pure
returns (address token0, address token1);
/// @return The number of token pairs configured
function getTokenPairsLength() external view returns (uint256);
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @return The quantity of pools configured for the specified token pair
function getTokenPairPoolsLength(address tokenA, address tokenB)
external
view
returns (uint256);
/// @param tokenA The address of tokenA
/// @param tokenB The address of tokenB
/// @param poolId The index of the pool in the pools mapping
/// @return feeNumerator The numerator that gets divided by the fee denominator
function getPoolFeeNumerator(
address tokenA,
address tokenB,
uint256 poolId
) external view returns (uint24 feeNumerator);
function getPoolAddress(address tokenA, address tokenB)
external
view
returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.7.6;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = 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++;
}
}
}
|
tokenA The address of tokenA tokenB The address of tokenB return token0 The address of the sorted token0 return token1 The address of the sorted token1
|
function getTokensSorted(address tokenA, address tokenB)
public
pure
override
returns (address token0, address token1)
{
if (tokenA < tokenB) {
token0 = tokenA;
token1 = tokenB;
token0 = tokenB;
token1 = tokenA;
}
}
| 9,865,351
|
./full_match/5/0x968a3b0DC3DaBE44b85d8F988f6d6cB97EAE1264/sources/contracts/MutantsVsMachine.sol
|
setter function to pause/start level three mint
|
function setPauseMintL3(bool _pauseMintL3) public onlyOwner {
pauseMintL3 = _pauseMintL3;
}
| 1,864,595
|
pragma solidity >=0.4.24;
import { ERC721Metadata } from "./openzeppelin-solidity/token/ERC721/ERC721Metadata.sol";
import "./openzeppelin-solidity/cryptography/ECDSA.sol";
import "./merkle.sol";
contract AnchorLike {
function getAnchorById(uint) public view returns (uint, bytes32, uint32);
}
contract KeyManagerLike {
function keyHasPurpose(bytes32, uint) public view returns (bool);
function getKey(bytes32) public view returns (bytes32, uint[] memory, uint32);
}
contract IdentityFactoryLike {
function createdIdentity(address) public view returns (bool);
}
contract CabbalToken is ERC721Metadata, MerkleVerifier {
using ECDSA for bytes32;
// --- Data ---
KeyManagerLike public key_manager;
AnchorLike public anchors;
IdentityFactoryLike public identity_factory;
// Base for constructing dynamic metadata token URIS
// the token uri also contains the registry address. uri + contract address + tokenId
string public uri;
// --- Compact Properties ---
// compact prop for "next_version"
bytes constant internal NEXT_VERSION = hex"0100000000000004";
// compact prop for "nfts"
bytes constant internal NFTS = hex"0100000000000014";
// Value of the Signature purpose for an identity. sha256('CENTRIFUGE@SIGNING')
// solium-disable-next-line
uint constant internal SIGNING_PURPOSE = 0x774a43710604e3ce8db630136980a6ba5a65b5e6686ee51009ed5f3fded6ea7e;
constructor (string memory name, string memory symbol, address anchors_, address identity_, address identity_factory_) ERC721Metadata(name, symbol) public {
anchors = AnchorLike(anchors_);
key_manager = KeyManagerLike(identity_);
identity_factory = IdentityFactoryLike(identity_factory_);
}
event Minted(address usr, uint tkn);
// --- Utils ---
function concat(bytes32 b1, bytes32 b2) pure internal returns (bytes memory) {
bytes memory result = new bytes(64);
assembly {
mstore(add(result, 32), b1)
mstore(add(result, 64), b2)
}
return result;
}
/**
* @dev Parses bytes and extracts a uint value
* @param data bytes From where to extract the index
* @return result the converted address
*/
function bytesToUint(bytes memory data) internal pure returns (uint) {
require(data.length <= 256, "slicing out of range");
return abi.decode(data, (uint));
}
/**
* @dev Parses a uint and returns the hex string
* @param payload uint
* @return string the corresponding hex string
*/
function uintToHexStr(uint payload) internal pure returns (string memory) {
if (payload == 0)
return "0";
// calculate string length
uint i = payload;
uint length;
while (i != 0) {
length++;
i = i >> 4;
}
// parse byte by byte and construct the string
i = payload;
uint mask = 15;
bytes memory result = new bytes(length);
uint k = length - 1;
while (i != 0) {
uint curr = (i & mask);
result[k--] = curr > 9 ? byte(55 + uint8(curr)) : byte(48 + uint8(curr));
i = i >> 4;
}
return string(result);
}
function equalBytes(bytes memory a, bytes memory b) internal pure returns (bool) {
if (a.length == b.length) {
for (uint i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
return false;
}
// --- NFT ---
function _checkAnchor(uint anchor, bytes32 data_root, bytes32 sig_root) internal view returns (bool) {
bytes32 doc_root;
(, doc_root, ) = anchors.getAnchorById(anchor);
if (data_root < sig_root) {
return doc_root == sha256(concat(data_root, sig_root));
} else {
return doc_root == sha256(concat(sig_root, data_root));
}
}
function tokenURI( uint token_id) external view returns (string memory) {
return string(abi.encodePacked(uri, "0x", uintToHexStr(uint(address(this))), "/0x", uintToHexStr(token_id)));
}
/**
* @dev Checks if the document is the latest version anchored
* @param data_root bytes32 hash of all data fields of the document which are signed
* @param next_anchor_id uint the next id to be anchored
*/
function _latestDoc( bytes32 data_root, uint next_anchor_id) internal view returns (bool) {
(, bytes32 next_merkle_root_, ) = anchors.getAnchorById(next_anchor_id);
return next_merkle_root_ == 0x0;
}
/**
* @dev Checks that provided document is signed by the given identity and validates and checks if the public key used is a valid SIGNING_KEY. Does not check if the signature root is part of the document root.
* @param anchor uint anchor ID
* @param data_root bytes32 hash of all data fields of the document which are signed
* @param signature bytes The signature used to sign the data root
*/
function _signed(uint anchor, bytes32 data_root, bytes memory signature) internal view {
// Get anchored block from anchor ID
(, , uint32 anchored_block) = anchors.getAnchorById(anchor);
// Extract the public key and identity address from the signature
address identity_ = data_root.toEthSignedMessageHash().recover(signature);
bytes32 pbKey_ = bytes32(uint(identity_) << 96);
// check that the identity being used has been created by the Centrifuge Identity Factory contract
require(identity_factory.createdIdentity(identity_), "Identity is not registered.");
// check that public key has signature purpose on provided identity
require(key_manager.keyHasPurpose(pbKey_, SIGNING_PURPOSE), "Signature key is not valid.");
// If key is revoked, anchor must be older the the key revocation
(, , uint32 revokedAt_) = key_manager.getKey(pbKey_);
if (revokedAt_ > 0) {
require(anchored_block < revokedAt_,"Document signed with a revoked key.");
}
}
/**
* @dev Checks that the passed in token proof matches the data for minting
* @param tkn uint The ID for the token to be minted
*/
function _checkTokenData(uint tkn, bytes memory property, bytes memory value) internal view returns (bool) {
if (bytesToUint(value) != tkn) {
return false;
}
return equalBytes(property, abi.encodePacked(hex"0100000000000014", address(this), hex"000000000000000000000000"));
}
/**
* @dev Mints a token to a specified address
* @param usr address deposit address of token
* @param tkn uint tokenID
*/
function _mint(address usr, uint tkn) internal {
super._mint(usr, tkn);
emit Minted(usr, tkn);
}
}
|
Checks that the passed in token proof matches the data for minting tkn uint The ID for the token to be minted/
|
function _checkTokenData(uint tkn, bytes memory property, bytes memory value) internal view returns (bool) {
if (bytesToUint(value) != tkn) {
return false;
}
return equalBytes(property, abi.encodePacked(hex"0100000000000014", address(this), hex"000000000000000000000000"));
}
| 5,455,190
|
pragma solidity 0.5.10;
import "../interfaces/IBlockRewardAuRa.sol";
import "../interfaces/IERC677.sol";
import "../interfaces/IGovernance.sol";
import "../interfaces/IStakingAuRa.sol";
import "../interfaces/IValidatorSetAuRa.sol";
import "../upgradeability/UpgradeableOwned.sol";
import "../libs/SafeMath.sol";
/// @dev Implements staking and withdrawal logic.
contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa {
using SafeMath for uint256;
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
uint256[] internal _pools;
uint256[] internal _poolsInactive;
uint256[] internal _poolsToBeElected;
uint256[] internal _poolsToBeRemoved;
uint256[] internal _poolsLikelihood;
uint256 internal _poolsLikelihoodSum;
mapping(uint256 => address[]) internal _poolDelegators;
mapping(uint256 => address[]) internal _poolDelegatorsInactive;
mapping(address => uint256[]) internal _delegatorPools;
mapping(address => mapping(uint256 => uint256)) internal _delegatorPoolsIndexes;
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch;
mapping(uint256 => uint256) internal _stakeInitial;
// Reserved storage slots to allow for layout changes in the future.
uint256[24] private ______gapForInternal;
/// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
uint256 public candidateMinStake;
/// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
uint256 public delegatorMinStake;
/// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator
/// before the specified staking epoch. Used by the `claimReward` function.
/// The first parameter is the pool id, the second one is delegator's address,
/// the third one is staking epoch number.
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot;
/// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified
/// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderedWithdrawAmount;
/// @dev The current total amount of staking tokens/coins ordered for withdrawal from
/// the specified pool by all of its stakers. Pool id is accepted as a parameter.
mapping(uint256 => uint256) public orderedWithdrawAmountTotal;
/// @dev The number of the staking epoch during which the specified staker ordered
/// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function
/// to allow the ordered amount to be claimed only in future staking epochs. The first parameter
/// is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderWithdrawEpoch;
/// @dev The delegator's index in the array returned by the `poolDelegators` getter.
/// Used by the `_removePoolDelegator` internal function. The first parameter is a pool id.
/// The second parameter is delegator's address.
/// If the value is zero, it may mean the array doesn't contain the delegator.
/// Check if the delegator is in the array using the `poolDelegators` getter.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorIndex;
/// @dev The delegator's index in the `poolDelegatorsInactive` array.
/// Used by the `_removePoolDelegatorInactive` internal function.
/// A delegator is considered inactive if they have withdrawn their stake from
/// the specified pool but haven't yet claimed an ordered amount.
/// The first parameter is a pool id. The second parameter is delegator's address.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorInactiveIndex;
/// @dev The pool's index in the array returned by the `getPoolsInactive` getter.
/// Used by the `_removePoolInactive` internal function. The pool id is accepted as a parameter.
mapping(uint256 => uint256) public poolInactiveIndex;
/// @dev The pool's index in the array returned by the `getPools` getter.
/// Used by the `_removePool` internal function. A pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `isPoolActive` getter.
mapping(uint256 => uint256) public poolIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter.
/// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeElected` getter.
mapping(uint256 => uint256) public poolToBeElectedIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter.
/// Used by the `_deletePoolToBeRemoved` internal function.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeRemoved` getter.
mapping(uint256 => uint256) public poolToBeRemovedIndex;
/// @dev A boolean flag indicating whether the reward was already taken
/// from the specified pool by the specified staker for the specified staking epoch.
/// The first parameter is the pool id, the second one is staker's address,
/// the third one is staking epoch number.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => mapping(uint256 => bool))) public rewardWasTaken;
/// @dev The amount of tokens currently staked into the specified pool by the specified
/// staker. Doesn't include the amount ordered for withdrawal.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public stakeAmount;
/// @dev The number of staking epoch before which the specified delegator placed their first
/// stake into the specified pool. If this is equal to zero, it means the delegator never
/// staked into the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeFirstEpoch;
/// @dev The number of staking epoch before which the specified delegator withdrew their stake
/// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means
/// the delegator still has some stake in the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeLastEpoch;
/// @dev The duration period (in blocks) at the end of staking epoch during which
/// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins.
uint256 public stakeWithdrawDisallowPeriod;
/// @dev The serial number of the current staking epoch.
uint256 public stakingEpoch;
/// @dev The duration of a staking epoch in blocks.
uint256 public stakingEpochDuration;
/// @dev The number of the first block of the current staking epoch.
uint256 public stakingEpochStartBlock;
/// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool.
/// Doesn't include the amount ordered for withdrawal.
/// The pool id is accepted as a parameter.
mapping(uint256 => uint256) public stakeAmountTotal;
/// @dev The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
/// @dev The block number of the last change in this contract.
/// Can be used by Staking DApp.
uint256 public lastChangeBlock;
/// @dev The address of the `Governance` contract.
IGovernance public governanceContract;
// Reserved storage slots to allow for layout changes in the future.
uint256[23] private ______gapForPublic;
// ============================================== Constants =======================================================
/// @dev The max number of candidates (including validators). This limit was determined through stress testing.
uint256 public constant MAX_CANDIDATES = 3000;
// ================================================ Events ========================================================
/// @dev Emitted by the `_addPool` internal function to signal that
/// a new pool is created.
/// @param poolStakingAddress The staking address of newly added pool.
/// @param poolMiningAddress The mining address of newly added pool.
/// @param poolId The id of newly added pool.
event AddedPool(address indexed poolStakingAddress, address indexed poolMiningAddress, uint256 poolId);
/// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified
/// amount of requested tokens/coins from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of the staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the claim was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event ClaimedOrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `moveStake` function to signal the staker moved the specified
/// amount of stake from one pool to another during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` moved the stake.
/// @param toPoolStakingAddress A staking address of the destination pool where the `staker` moved the stake.
/// @param staker The address of the staker who moved the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved.
/// @param amount The stake amount which was moved.
/// @param fromPoolId An id of the pool from which the `staker` moved the stake.
/// @param toPoolId An id of the destination pool where the `staker` moved the stake.
event MovedStake(
address fromPoolStakingAddress,
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId,
uint256 toPoolId
);
/// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the
/// specified amount of their stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker`
/// ordered a withdrawal of the `amount`.
/// @param staker The address of the staker that ordered the withdrawal of the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the order was made.
/// @param amount The ordered withdrawal amount. Can be either positive or negative.
/// See the `orderWithdraw` function.
/// @param fromPoolId An id of the pool from which the `staker` ordered a withdrawal of the `amount`.
event OrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
int256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified
/// amount for the specified pool during the specified staking epoch.
/// @param toPoolStakingAddress A staking address of the pool into which the `staker` placed the stake.
/// @param staker The address of the staker that placed the stake.
/// @param stakingEpoch The serial number of the staking epoch during which the stake was made.
/// @param amount The stake amount.
/// @param toPoolId An id of the pool into which the `staker` placed the stake.
event PlacedStake(
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 toPoolId
);
/// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified
/// amount of a stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event WithdrewStake(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
// ============================================== Modifiers =======================================================
/// @dev Ensures the transaction gas price is not zero.
modifier gasPriceIsValid() {
require(tx.gasprice != 0);
_;
}
/// @dev Ensures the caller is the BlockRewardAuRa contract address.
modifier onlyBlockRewardContract() {
require(msg.sender == validatorSetContract.blockRewardContract());
_;
}
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized());
_;
}
/// @dev Ensures the caller is the ValidatorSetAuRa contract address.
modifier onlyValidatorSetContract() {
require(msg.sender == address(validatorSetContract));
_;
}
// =============================================== Setters ========================================================
/// @dev Fallback function. Prevents direct sending native coins to this contract.
function () payable external {
revert();
}
/// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter),
/// moves the specified amount of staking tokens/coins from the candidate's staking address
/// to the candidate's pool, and returns a unique id of the newly added pool.
/// A participant calls this function using their staking address when
/// they want to create a pool. This is a wrapper for the `stake` function.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `msg.sender`.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function addPool(
uint256 _amount,
address _miningAddress,
string calldata _name,
string calldata _description
) external payable returns(uint256) {
return _addPool(_amount, msg.sender, _miningAddress, false, _name, _description);
}
/// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array
/// depending on their own stake in their own pool when they become removable. This allows the
/// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool.
/// Called by the `ValidatorSet.clearUnremovableValidator` function.
/// @param _unremovablePoolId The pool id of the unremovable validator.
function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract {
require(_unremovablePoolId != 0);
if (stakeAmount[_unremovablePoolId][address(0)] != 0) {
_addPoolToBeElected(_unremovablePoolId);
_setLikelihood(_unremovablePoolId);
} else {
_addPoolToBeRemoved(_unremovablePoolId);
}
}
/// @dev Increments the serial number of the current staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch.
function incrementStakingEpoch() external onlyValidatorSetContract {
stakingEpoch++;
}
/// @dev Initializes the network parameters.
/// Can only be called by the constructor of the `InitializerAuRa` contract or owner.
/// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract.
/// @param _governanceContract The address of the `Governance` contract.
/// @param _initialIds The array of initial validators' pool ids.
/// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei.
/// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei.
/// @param _stakingEpochDuration The duration of a staking epoch in blocks
/// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa).
/// @param _stakingEpochStartBlock The number of the first block of initial staking epoch
/// (must be zero if the network is starting from genesis block).
/// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch
/// during which participants cannot stake/withdraw/order/claim their staking tokens/coins
/// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa).
function initialize(
address _validatorSetContract,
address _governanceContract,
uint256[] calldata _initialIds,
uint256 _delegatorMinStake,
uint256 _candidateMinStake,
uint256 _stakingEpochDuration,
uint256 _stakingEpochStartBlock,
uint256 _stakeWithdrawDisallowPeriod
) external {
require(_validatorSetContract != address(0));
require(_initialIds.length > 0);
require(_delegatorMinStake != 0);
require(_candidateMinStake != 0);
require(_stakingEpochDuration != 0);
require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod);
require(_stakeWithdrawDisallowPeriod != 0);
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
require(!isInitialized()); // initialization can only be done once
validatorSetContract = IValidatorSetAuRa(_validatorSetContract);
governanceContract = IGovernance(_governanceContract);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
for (uint256 i = 0; i < _initialIds.length; i++) {
require(_initialIds[i] != 0);
_addPoolActive(_initialIds[i], false);
if (_initialIds[i] != unremovablePoolId) {
_addPoolToBeRemoved(_initialIds[i]);
}
}
delegatorMinStake = _delegatorMinStake;
candidateMinStake = _candidateMinStake;
stakingEpochDuration = _stakingEpochDuration;
stakingEpochStartBlock = _stakingEpochStartBlock;
stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod;
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Makes initial validator stakes. Can only be called by the owner
/// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`),
/// or after the network starts from genesis (`stakingEpochStartBlock` == 0).
/// Cannot be called more than once and cannot be called when starting from genesis.
/// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`.
/// @param _totalAmount The initial validator total stake amount (for all initial validators).
function initialValidatorStake(uint256 _totalAmount) external onlyOwner {
uint256 currentBlock = _getCurrentBlockNumber();
require(stakingEpoch == 0);
require(currentBlock < stakingEpochStartBlock || stakingEpochStartBlock == 0);
require(_thisBalance() == _totalAmount);
require(_totalAmount % _pools.length == 0);
uint256 stakingAmount = _totalAmount.div(_pools.length);
uint256 stakingEpochStartBlock_ = stakingEpochStartBlock;
// Temporarily set `stakingEpochStartBlock` to the current block number
// to avoid revert in the `_stake` function
stakingEpochStartBlock = currentBlock;
for (uint256 i = 0; i < _pools.length; i++) {
uint256 poolId = _pools[i];
address stakingAddress = validatorSetContract.stakingAddressById(poolId);
require(stakeAmount[poolId][address(0)] == 0);
_stake(stakingAddress, stakingAddress, stakingAmount);
_stakeInitial[poolId] = stakingAmount;
}
// Restore `stakingEpochStartBlock` value
stakingEpochStartBlock = stakingEpochStartBlock_;
}
/// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the
/// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function
/// when a pool must be removed by the algorithm.
/// @param _poolId The id of the pool to be removed.
function removePool(uint256 _poolId) external onlyValidatorSetContract {
_removePool(_poolId);
}
/// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function when pools must be removed by the algorithm.
function removePools() external onlyValidatorSetContract {
uint256[] memory poolsToRemove = _poolsToBeRemoved;
for (uint256 i = 0; i < poolsToRemove.length; i++) {
_removePool(poolsToRemove[i]);
}
}
/// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which
/// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool,
/// they should call this function from their staking address. A validator cannot remove their pool while
/// they are an `unremovable validator`.
function removeMyPool() external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(msg.sender);
require(poolId != 0);
// initial validator cannot remove their pool during the initial staking epoch
require(stakingEpoch > 0 || !validatorSetContract.isValidatorById(poolId));
require(poolId != validatorSetContract.unremovableValidator());
_removePool(poolId);
}
/// @dev Sets the number of the first block in the upcoming staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch.
/// @param _blockNumber The number of the very first block in the upcoming staking epoch.
function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract {
stakingEpochStartBlock = _blockNumber;
}
/// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want
/// to move their tokens/coins from one pool to another without withdrawing their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the source pool.
/// @param _toPoolStakingAddress The staking address of the target pool.
/// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function moveStake(
address _fromPoolStakingAddress,
address _toPoolStakingAddress,
uint256 _amount
) external {
require(_fromPoolStakingAddress != _toPoolStakingAddress);
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
uint256 toPoolId = validatorSetContract.idByStakingAddress(_toPoolStakingAddress);
address staker = msg.sender;
_withdraw(_fromPoolStakingAddress, staker, _amount);
_stake(_toPoolStakingAddress, staker, _amount);
emit MovedStake(
_fromPoolStakingAddress,
_toPoolStakingAddress,
staker,
stakingEpoch,
_amount,
fromPoolId,
toPoolId
);
}
/// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of
/// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract.
/// A staker calls this function when they want to make a stake into a pool.
/// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used instead.
function stake(address _toPoolStakingAddress, uint256 _amount) external payable {
_stake(_toPoolStakingAddress, _amount);
}
/// @dev Moves the specified amount of staking tokens/coins from the staking address of
/// the specified pool to the staker's address. A staker calls this function when they want to withdraw
/// their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function withdraw(address _fromPoolStakingAddress, uint256 _amount) external {
address payable staker = msg.sender;
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
_withdraw(_fromPoolStakingAddress, staker, _amount);
_sendWithdrawnStakeAmount(staker, _amount);
emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId);
}
/// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the
/// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using
/// the `claimOrderedWithdraw` function.
/// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn.
/// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or
/// increase their withdrawal amount. A negative value means the staker wants to decrease a
/// withdrawal amount that was previously set. The amount cannot exceed the value returned by the
/// `maxWithdrawOrderAllowed` getter.
function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
address staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(_isWithdrawAllowed(poolId, delegatorOrZero != address(0)));
uint256 newOrderedAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[poolId];
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero];
uint256 newStakeAmountTotal = stakeAmountTotal[poolId];
if (_amount > 0) {
uint256 amount = uint256(_amount);
// How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment?
require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker));
newOrderedAmount = newOrderedAmount.add(amount);
newOrderedAmountTotal = newOrderedAmountTotal.add(amount);
newStakeAmount = newStakeAmount.sub(amount);
newStakeAmountTotal = newStakeAmountTotal.sub(amount);
orderWithdrawEpoch[poolId][delegatorOrZero] = stakingEpoch;
} else {
uint256 amount = uint256(-_amount);
newOrderedAmount = newOrderedAmount.sub(amount);
newOrderedAmountTotal = newOrderedAmountTotal.sub(amount);
newStakeAmount = newStakeAmount.add(amount);
newStakeAmountTotal = newStakeAmountTotal.add(amount);
}
orderedWithdrawAmount[poolId][delegatorOrZero] = newOrderedAmount;
orderedWithdrawAmountTotal[poolId] = newOrderedAmountTotal;
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
stakeAmountTotal[poolId] = newStakeAmountTotal;
if (staker == _poolStakingAddress) {
// Initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `candidateMinStake`
require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_amount > 0) { // if the validator orders the `_amount` for withdrawal
if (newStakeAmount == 0 && poolId != unremovablePoolId) {
// If the removable validator orders their entire stake,
// mark their pool as `to be removed`
_addPoolToBeRemoved(poolId);
}
} else {
// If the validator wants to reduce withdrawal value,
// add their pool as `active` if it hasn't already done
_addPoolActive(poolId, poolId != unremovablePoolId);
}
} else {
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `delegatorMinStake`
require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake);
if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal
if (newStakeAmount == 0) {
// If the delegator orders their entire stake,
// remove the delegator from delegator list of the pool
_removePoolDelegator(poolId, staker);
}
} else {
// If the delegator wants to reduce withdrawal value,
// add them to delegator list of the pool if it hasn't already done
_addPoolDelegator(poolId, staker);
}
// Remember stake movement to use it later in the `claimReward` function
_snapshotDelegatorStake(poolId, staker);
}
_setLikelihood(poolId);
emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount, poolId);
}
/// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with
/// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter.
/// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn.
function claimOrderedWithdraw(address _poolStakingAddress) external {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(poolId != 0);
address payable staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(stakingEpoch > orderWithdrawEpoch[poolId][delegatorOrZero]);
require(!_isPoolBanned(poolId, delegatorOrZero != address(0)));
uint256 claimAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
require(claimAmount != 0);
orderedWithdrawAmount[poolId][delegatorOrZero] = 0;
orderedWithdrawAmountTotal[poolId] = orderedWithdrawAmountTotal[poolId].sub(claimAmount);
if (stakeAmount[poolId][delegatorOrZero] == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, staker);
}
_sendWithdrawnStakeAmount(staker, claimAmount);
emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount, poolId);
}
/// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
candidateMinStake = _minStake;
}
/// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
delegatorMinStake = _minStake;
}
// =============================================== Getters ========================================================
/// @dev Returns an array of the current active pools (the pool ids of candidates and validators).
/// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive`
/// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active
/// if its address has at least the minimum stake and this stake is not ordered to be withdrawn.
function getPools() external view returns(uint256[] memory) {
return _pools;
}
/// @dev Returns an array of the current inactive pools (the pool ids of former candidates).
/// A pool can be added to this array with the `_addPoolInactive` internal function which is called
/// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address
/// has zero stake, or if its entire stake is ordered to be withdrawn.
function getPoolsInactive() external view returns(uint256[] memory) {
return _poolsInactive;
}
/// @dev Returns the array of stake amounts for each corresponding
/// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts.
/// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last
/// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool
/// (see the `_setLikelihood` internal function).
/// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length
/// of the `poolsToBeElected` array.
/// `uint256 sum` - The total sum of the amounts.
function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) {
return (_poolsLikelihood, _poolsLikelihoodSum);
}
/// @dev Returns the list of pools (their ids) which will participate in a new validator set
/// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools
/// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch).
/// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions.
function getPoolsToBeElected() external view returns(uint256[] memory) {
return _poolsToBeElected;
}
/// @dev Returns the list of pools (their ids) which will be removed by the
/// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block
/// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved`
/// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's
/// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool.
function getPoolsToBeRemoved() external view returns(uint256[] memory) {
return _poolsToBeRemoved;
}
/// @dev Returns the list of pool ids into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
/// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0.
/// @param _length The max number of items to return.
function getDelegatorPools(
address _delegator,
uint256 _offset,
uint256 _length
) external view returns(uint256[] memory result) {
uint256[] storage delegatorPools = _delegatorPools[_delegator];
if (_length == 0) {
return delegatorPools;
}
uint256 maxLength = delegatorPools.length.sub(_offset);
result = new uint256[](_length > maxLength ? maxLength : _length);
for (uint256 i = 0; i < result.length; i++) {
result[i] = delegatorPools[_offset + i];
}
}
/// @dev Returns the length of the list of pools into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
function getDelegatorPoolsLength(address _delegator) external view returns(uint256) {
return _delegatorPools[_delegator].length;
}
/// @dev Determines whether staking/withdrawal operations are allowed at the moment.
/// Used by all staking/withdrawal functions.
function areStakeAndWithdrawAllowed() public view returns(bool) {
uint256 currentBlock = _getCurrentBlockNumber();
if (currentBlock < stakingEpochStartBlock) return false;
uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod;
if (stakingEpochStartBlock == 0) allowedDuration++;
return currentBlock - stakingEpochStartBlock < allowedDuration;
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
/// @dev Returns a flag indicating whether a specified id is in the `pools` array.
/// See the `getPools` getter.
/// @param _poolId An id of the pool.
function isPoolActive(uint256 _poolId) public view returns(bool) {
uint256 index = poolIndex[_poolId];
return index < _pools.length && _pools[index] == _poolId;
}
/// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker
/// at the moment. Used by the `withdraw` and `moveStake` functions.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be made.
/// @param _staker The staker address that is going to withdraw.
function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
bool isDelegator = _poolStakingAddress != _staker;
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
uint256 canWithdraw = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canWithdraw = canWithdraw.sub(_stakeInitial[poolId]);
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// The pool is not a validator and is not going to become one,
// so the staker can only withdraw staked amount minus already
// ordered amount
return canWithdraw;
}
// The pool is a validator (active or pending), so the staker can only
// withdraw staked amount minus already ordered amount but
// no more than the amount staked during the current staking epoch
uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
if (canWithdraw > stakedDuringEpoch) {
canWithdraw = stakedDuringEpoch;
}
return canWithdraw;
}
/// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the
/// specified staker at the moment. Used by the `orderWithdraw` function.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered.
/// @param _staker The staker address that is going to order the withdrawal.
function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
bool isDelegator = _poolStakingAddress != _staker;
address delegatorOrZero = isDelegator ? _staker : address(0);
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// If the pool is a candidate (not an active validator and not pending one),
// no one can order withdrawal from the `_poolStakingAddress`, but
// anyone can withdraw immediately (see the `maxWithdrawAllowed` getter)
return 0;
}
// If the pool is an active or pending validator, the staker can order withdrawal
// up to their total staking amount minus an already ordered amount
// minus an amount staked during the current staking epoch
uint256 canOrder = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canOrder = canOrder.sub(_stakeInitial[poolId]);
}
return canOrder.sub(stakeAmountByCurrentEpoch(poolId, delegatorOrZero));
}
/// @dev Returns an array of the current active delegators of the specified pool.
/// A delegator is considered active if they have staked into the specified
/// pool and their stake is not ordered to be withdrawn.
/// @param _poolId The pool id.
function poolDelegators(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegators[_poolId];
}
/// @dev Returns an array of the current inactive delegators of the specified pool.
/// A delegator is considered inactive if their entire stake is ordered to be withdrawn
/// but not yet claimed.
/// @param _poolId The pool id.
function poolDelegatorsInactive(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegatorsInactive[_poolId];
}
/// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker
/// during the current staking epoch (see the `stakingEpoch` getter).
/// Used by the `stake`, `withdraw`, and `orderWithdraw` functions.
/// @param _poolId The pool id.
/// @param _delegatorOrZero The delegator's address (or zero address if the staker is the pool itself).
function stakeAmountByCurrentEpoch(uint256 _poolId, address _delegatorOrZero)
public
view
returns(uint256)
{
return _stakeAmountByEpoch[_poolId][_delegatorOrZero][stakingEpoch];
}
/// @dev Returns the number of the last block of the current staking epoch.
function stakingEpochEndBlock() public view returns(uint256) {
uint256 startBlock = stakingEpochStartBlock;
return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1);
}
// ============================================== Internal ========================================================
/// @dev Adds the specified pool id to the array of active pools returned by
/// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions.
/// @param _poolId The pool id added to the array of active pools.
/// @param _toBeElected The boolean flag which defines whether the specified id should be
/// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
function _addPoolActive(uint256 _poolId, bool _toBeElected) internal {
if (!isPoolActive(_poolId)) {
poolIndex[_poolId] = _pools.length;
_pools.push(_poolId);
require(_pools.length <= _getMaxCandidates());
}
_removePoolInactive(_poolId);
if (_toBeElected) {
_addPoolToBeElected(_poolId);
}
}
/// @dev Adds the specified pool id to the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by the `_removePool` internal function.
/// @param _poolId The pool id added to the array of inactive pools.
function _addPoolInactive(uint256 _poolId) internal {
uint256 index = poolInactiveIndex[_poolId];
uint256 length = _poolsInactive.length;
if (index >= length || _poolsInactive[index] != _poolId) {
poolInactiveIndex[_poolId] = length;
_poolsInactive.push(_poolId);
}
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeElected`
/// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id added to the `poolsToBeElected` array.
function _addPoolToBeElected(uint256 _poolId) internal {
uint256 index = poolToBeElectedIndex[_poolId];
uint256 length = _poolsToBeElected.length;
if (index >= length || _poolsToBeElected[index] != _poolId) {
poolToBeElectedIndex[_poolId] = length;
_poolsToBeElected.push(_poolId);
_poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter
}
_deletePoolToBeRemoved(_poolId);
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeRemoved`
/// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id added to the `poolsToBeRemoved` array.
function _addPoolToBeRemoved(uint256 _poolId) internal {
uint256 index = poolToBeRemovedIndex[_poolId];
uint256 length = _poolsToBeRemoved.length;
if (index >= length || _poolsToBeRemoved[index] != _poolId) {
poolToBeRemovedIndex[_poolId] = length;
_poolsToBeRemoved.push(_poolId);
}
_deletePoolToBeElected(_poolId);
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions.
/// See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id deleted from the `poolsToBeElected` array.
function _deletePoolToBeElected(uint256 _poolId) internal {
if (_poolsToBeElected.length != _poolsLikelihood.length) return;
uint256 indexToDelete = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _poolId) {
if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) {
_poolsLikelihoodSum -= _poolsLikelihood[indexToDelete];
} else {
_poolsLikelihoodSum = 0;
}
uint256 lastPoolIndex = _poolsToBeElected.length - 1;
uint256 lastPool = _poolsToBeElected[lastPoolIndex];
_poolsToBeElected[indexToDelete] = lastPool;
_poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex];
poolToBeElectedIndex[lastPool] = indexToDelete;
poolToBeElectedIndex[_poolId] = 0;
_poolsToBeElected.length--;
_poolsLikelihood.length--;
}
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions.
/// See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id deleted from the `poolsToBeRemoved` array.
function _deletePoolToBeRemoved(uint256 _poolId) internal {
uint256 indexToDelete = poolToBeRemovedIndex[_poolId];
if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _poolId) {
uint256 lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1];
_poolsToBeRemoved[indexToDelete] = lastPool;
poolToBeRemovedIndex[lastPool] = indexToDelete;
poolToBeRemovedIndex[_poolId] = 0;
_poolsToBeRemoved.length--;
}
}
/// @dev Removes the specified pool id from the array of active pools returned by
/// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions.
/// @param _poolId The pool id removed from the array of active pools.
function _removePool(uint256 _poolId) internal {
uint256 indexToRemove = poolIndex[_poolId];
if (_pools.length > indexToRemove && _pools[indexToRemove] == _poolId) {
uint256 lastPool = _pools[_pools.length - 1];
_pools[indexToRemove] = lastPool;
poolIndex[lastPool] = indexToRemove;
poolIndex[_poolId] = 0;
_pools.length--;
}
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
} else {
_addPoolInactive(_poolId);
}
_deletePoolToBeElected(_poolId);
_deletePoolToBeRemoved(_poolId);
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Removes the specified pool id from the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and
/// `_removePool` internal functions.
/// @param _poolId The pool id removed from the array of inactive pools.
function _removePoolInactive(uint256 _poolId) internal {
uint256 indexToRemove = poolInactiveIndex[_poolId];
if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _poolId) {
uint256 lastPool = _poolsInactive[_poolsInactive.length - 1];
_poolsInactive[indexToRemove] = lastPool;
poolInactiveIndex[lastPool] = indexToRemove;
poolInactiveIndex[_poolId] = 0;
_poolsInactive.length--;
}
}
/// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _stakingAddress The staking address of the new candidate.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `_stakingAddress`.
/// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called
/// by the `onTokenTransfer` function.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function _addPool(
uint256 _amount,
address _stakingAddress,
address _miningAddress,
bool _byOnTokenTransfer,
string memory _name,
string memory _description
) internal returns(uint256) {
uint256 poolId = validatorSetContract.addPool(_miningAddress, _stakingAddress, _name, _description);
if (_byOnTokenTransfer) {
_stake(_stakingAddress, _stakingAddress, _amount);
} else {
_stake(_stakingAddress, _amount);
}
emit AddedPool(_stakingAddress, _miningAddress, poolId);
return poolId;
}
/// @dev Adds the specified address to the array of the current active delegators of the specified pool.
/// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 index = poolDelegatorIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
_removePoolDelegatorInactive(_poolId, _delegator);
}
/// @dev Adds the specified address to the array of the current inactive delegators of the specified pool.
/// Used by the `_removePoolDelegator` internal function.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 index = poolDelegatorInactiveIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorInactiveIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
}
/// @dev Removes the specified address from the array of the current active delegators of the specified pool.
/// Used by the withdrawal functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 indexToRemove = poolDelegatorIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorIndex[_poolId][_delegator] = 0;
delegators.length--;
}
if (orderedWithdrawAmount[_poolId][_delegator] != 0) {
_addPoolDelegatorInactive(_poolId, _delegator);
} else {
_removePoolDelegatorInactive(_poolId, _delegator);
}
}
/// @dev Removes the specified address from the array of the inactive delegators of the specified pool.
/// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 indexToRemove = poolDelegatorInactiveIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorInactiveIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorInactiveIndex[_poolId][_delegator] = 0;
delegators.length--;
}
}
function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal;
/// @dev Calculates (updates) the probability of being selected as a validator for the specified pool
/// and updates the total sum of probability coefficients. Actually, the probability is equal to the
/// amount totally staked into the pool. See the `getPoolsLikelihood` getter.
/// Used by the staking and withdrawal functions.
/// @param _poolId An id of the pool for which the probability coefficient must be updated.
function _setLikelihood(uint256 _poolId) internal {
lastChangeBlock = _getCurrentBlockNumber();
(bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolId);
if (!isToBeElected) return;
uint256 oldValue = _poolsLikelihood[index];
uint256 newValue = stakeAmountTotal[_poolId];
_poolsLikelihood[index] = newValue;
if (newValue >= oldValue) {
_poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue);
} else {
_poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue);
}
}
/// @dev Makes a snapshot of the amount currently staked by the specified delegator
/// into the specified pool. Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions.
/// @param _poolId An id of the pool.
/// @param _delegator The address of the delegator.
function _snapshotDelegatorStake(uint256 _poolId, address _delegator) internal {
uint256 nextStakingEpoch = stakingEpoch + 1;
uint256 newAmount = stakeAmount[_poolId][_delegator];
delegatorStakeSnapshot[_poolId][_delegator][nextStakingEpoch] =
(newAmount != 0) ? newAmount : uint256(-1);
if (stakeFirstEpoch[_poolId][_delegator] == 0) {
stakeFirstEpoch[_poolId][_delegator] = nextStakingEpoch;
}
stakeLastEpoch[_poolId][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0;
}
function _stake(address _toPoolStakingAddress, uint256 _amount) internal;
/// @dev The internal function used by the `_stake`, `moveStake`, `initialValidatorStake`, `_addPool` functions.
/// See the `stake` public function for more details.
/// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked.
/// @param _staker The staker's address.
/// @param _amount The amount of tokens/coins to be staked.
function _stake(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(poolId != 0);
require(_amount != 0);
require(!validatorSetContract.isValidatorIdBanned(poolId));
require(areStakeAndWithdrawAllowed());
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].add(_amount);
if (_staker == _poolStakingAddress) {
// The staked amount must be at least CANDIDATE_MIN_STAKE
require(newStakeAmount >= candidateMinStake);
} else {
// The staked amount must be at least DELEGATOR_MIN_STAKE
require(newStakeAmount >= delegatorMinStake);
// The delegator cannot stake into the pool of the candidate which hasn't self-staked.
// Also, that candidate shouldn't want to withdraw all their funds.
require(stakeAmount[poolId][address(0)] != 0);
}
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
stakeAmountByCurrentEpoch(poolId, delegatorOrZero).add(_amount);
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].add(_amount);
if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate
// Add `_poolStakingAddress` to the array of pools
_addPoolActive(poolId, poolId != validatorSetContract.unremovableValidator());
} else {
// Add `_staker` to the array of pool's delegators
_addPoolDelegator(poolId, _staker);
// Save/update amount value staked by the delegator
_snapshotDelegatorStake(poolId, _staker);
// Remember that the delegator (`_staker`) has ever staked into `_poolStakingAddress`
uint256[] storage delegatorPools = _delegatorPools[_staker];
uint256 delegatorPoolsLength = delegatorPools.length;
uint256 index = _delegatorPoolsIndexes[_staker][poolId];
bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != poolId;
if (neverStakedBefore) {
_delegatorPoolsIndexes[_staker][poolId] = delegatorPoolsLength;
delegatorPools.push(poolId);
}
if (delegatorPoolsLength == 0) {
// If this is the first time the delegator stakes,
// make sure the delegator has never been a mining address
require(validatorSetContract.hasEverBeenMiningAddress(_staker) == 0);
}
}
_setLikelihood(poolId);
emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount, poolId);
}
/// @dev The internal function used by the `withdraw` and `moveStake` functions.
/// See the `withdraw` public function for more details.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _staker The staker's address.
/// @param _amount The amount of the tokens/coins to be withdrawn.
function _withdraw(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
// How much can `_staker` withdraw from `_poolStakingAddress` at the moment?
require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker));
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].sub(_amount);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and min allowed stake
uint256 minAllowedStake;
if (_poolStakingAddress == _staker) {
// initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
minAllowedStake = candidateMinStake;
} else {
minAllowedStake = delegatorMinStake;
}
require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake);
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
uint256 amountByEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
amountByEpoch >= _amount ? amountByEpoch - _amount : 0;
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].sub(_amount);
if (newStakeAmount == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, _staker);
}
if (_staker != _poolStakingAddress) {
_snapshotDelegatorStake(poolId, _staker);
}
_setLikelihood(poolId);
}
/// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions.
/// Contains a common logic for these functions.
/// @param _poolId The id of the pool from which the tokens/coins are withdrawn.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn.
/// @param _staker The staker's address.
function _withdrawCheckPool(uint256 _poolId, address _poolStakingAddress, address _staker) internal {
if (_staker == _poolStakingAddress) {
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_poolId != unremovablePoolId) {
if (validatorSetContract.isValidatorById(_poolId)) {
_addPoolToBeRemoved(_poolId);
} else {
_removePool(_poolId);
}
}
} else {
_removePoolDelegator(_poolId, _staker);
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
}
}
}
/// @dev Returns the current block number. Needed mostly for unit tests.
function _getCurrentBlockNumber() internal view returns(uint256) {
return block.number;
}
/// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter.
/// Finds the stake amount made by a specified delegator into a specified pool before a specified
/// staking epoch.
function _getDelegatorStake(
uint256 _epoch,
uint256 _firstEpoch,
uint256 _prevDelegatorStake,
uint256 _poolId,
address _delegator
) internal view returns(uint256 delegatorStake) {
while (true) {
delegatorStake = delegatorStakeSnapshot[_poolId][_delegator][_epoch];
if (delegatorStake != 0) {
delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake;
break;
} else if (_epoch == _firstEpoch) {
delegatorStake = _prevDelegatorStake;
break;
}
_epoch--;
}
}
/// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant.
/// Needed mostly for unit tests.
function _getMaxCandidates() internal pure returns(uint256) {
return MAX_CANDIDATES;
}
/// @dev Returns a boolean flag indicating whether the specified pool is fully empty
/// (all stakes are withdrawn including ordered withdrawals).
/// @param _poolId An id of the pool.
function _isPoolEmpty(uint256 _poolId) internal view returns(bool) {
return stakeAmountTotal[_poolId] == 0 && orderedWithdrawAmountTotal[_poolId] == 0;
}
/// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
/// Used by the `_setLikelihood` internal function.
/// @param _poolId An id of the pool.
/// @return `bool toBeElected` - The boolean flag indicating whether the `_poolId` is in the
/// `poolsToBeElected` array.
/// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`.
function _isPoolToBeElected(uint256 _poolId) internal view returns(bool toBeElected, uint256 index) {
index = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _poolId) {
return (true, index);
}
return (false, 0);
}
/// @dev Returns `true` if the specified pool is banned or the pool is under a governance ballot.
/// Used by the `_isWithdrawAllowed` internal function and the `claimOrderedWithdraw` function.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isPoolBanned(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isDelegator) {
if (validatorSetContract.areIdDelegatorsBanned(_poolId)) {
// The delegator cannot withdraw from the banned validator pool until the ban is expired
return true;
}
} else {
if (validatorSetContract.isValidatorIdBanned(_poolId)) {
// The banned validator cannot withdraw from their pool until the ban is expired
return true;
} else if (governanceContract != IGovernance(0) && governanceContract.isValidatorUnderBallot(_poolId)) {
// There is an active ballot in the Governance contract for this validator removal
return true;
}
}
return false;
}
/// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment.
/// Used by all withdrawal functions.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isWithdrawAllowed(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isPoolBanned(_poolId, _isDelegator)) {
return false;
}
if (!areStakeAndWithdrawAllowed()) {
return false;
}
return true;
}
/// @dev Returns the balance of this contract in staking tokens or coins
/// depending on implementation.
function _thisBalance() internal view returns(uint256);
}
|
Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array depending on their own stake in their own pool when they become removable. This allows the `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool. Called by the `ValidatorSet.clearUnremovableValidator` function. _unremovablePoolId The pool id of the unremovable validator.
|
function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract {
require(_unremovablePoolId != 0);
if (stakeAmount[_unremovablePoolId][address(0)] != 0) {
_addPoolToBeElected(_unremovablePoolId);
_setLikelihood(_unremovablePoolId);
_addPoolToBeRemoved(_unremovablePoolId);
}
}
| 13,080,959
|
/**
*Submitted for verification at Etherscan.io on 2020-08-11
*/
pragma solidity 0.6.0;
/**
* @title Offering contract
* @dev Offering logic and mining logic
*/
contract Nest_NToken_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
// Offering data structure
struct Nest_NToken_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_NToken_OfferPriceData [] _prices; // Array used to save offers
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // nestToken
Nest_3_Abonus _abonus; // Bonus pool
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint256 _ownerMining = 5; // Creator ratio
uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount
uint32 _blockLimit = 25; // Block interval upper limit
uint256 _blockAttenuation = 2400000; // Block decay interval
mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee
mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount
uint256[10] _attenuationAmount; // Mining decay list
// Log token contract address
event OfferTokenContractAddress(address contractAddress);
// Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining);
// Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
// Log current block, current block mined amount, token address
event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress);
// Log offering block, token address, token offered times
event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes);
/**
* Initialization method
* @param voteFactory Voting contract address
**/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
uint256 blockAmount = 4 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(8).div(10);
}
}
/**
* Reset voting contract method
* @param voteFactory Voting contract address
**/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
}
/**
* Offering method
* @param ethAmount ETH amount
* @param erc20Amount Erc20 token amount
* @param erc20Address Erc20 token address
**/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address);
require(nTokenAddress != address(0x0));
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
_abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress);
// Mining
if (_blockOfferAmount[block.number][erc20Address] == 0) {
uint256 miningAmount = oreDrawing(nTokenAddress);
Nest_NToken nToken = Nest_NToken(nTokenAddress);
nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100));
_blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100));
}
_blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
**/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_NToken_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
/**
* Withdraw offer assets
* @param contractAddress Offer address
**/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner);
offerPriceData.serviceCharge = 0;
}
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* Offering mining
* @param ntoken NToken address
**/
function oreDrawing(address ntoken) private returns(uint256) {
Nest_NToken miningToken = Nest_NToken(ntoken);
(uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo();
uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock));
miningToken.increaseTotal(miningAmount);
emit OreDrawingLog(block.number, miningAmount, ntoken);
return miningAmount;
}
/**
* Retrieve mining
* @param token Token address
**/
function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) {
// Block mining amount*offer fee/block offer fee
uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
// Transfer NToken
Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token)));
require(nToken.transfer(address(owner), miningAmount), "Transfer failure");
emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]);
return miningAmount;
}
// Compare order prices
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Check contract status
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint256) {
return _blockLimit;
}
// View taker fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View minimum offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View block offering amount
function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) {
return _blockOfferAmount[blockNum][token];
}
// View offering block mining amount
function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) {
return _blockMining[blockNum][token];
}
// View offering mining amount
function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
}
}
// View the owner allocation ratio
function checkOwnerMining() public view returns(uint256) {
return _ownerMining;
}
// View the mining decay
function checkAttenuationAmount(uint256 num) public view returns(uint256) {
return _attenuationAmount[num];
}
// Modify taker order fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify block interval upper limit
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
// Modify offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_offerSpan = num;
}
// Modify price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
// Modify the owner allocation ratio
function changeOwnerMining(uint256 num) public onlyOwner {
_ownerMining = num;
}
// Modify the mining decay
function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner {
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(top).div(bottom);
}
}
// Vote administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form, write the string into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
}
// Price contract
interface Nest_3_OfferPrice {
// Add price data
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external;
// Modify price
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external;
function updateAndCheckPricePrivate(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount);
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether an administrator
function checkOwners(address man) external view returns (bool);
}
// NToken contract
interface Nest_NToken {
// Additional issuance
function increaseTotal(uint256 value) external;
// Check mining information
function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock);
// Check creator
function checkBidder() external view returns(address);
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);
}
// NToken mapping contract
interface Nest_NToken_TokenMapping {
// Check token mapping
function checkTokenMapping(address token) external view returns (address);
}
// Bonus pool contract
interface Nest_3_Abonus {
function switchToEth(address token) external payable;
function switchToEthForNTokenOffer(address token) external payable;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(ERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
|
Search the contract address list of the target account (reverse order) start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) count Maximum number of records to return maxFindCount The max index to search owner Target account address return Separate the offer records with symbols. use , to divide fields: uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge/ Buffer array used to generate result string Calculate search interval i and end Loop search, write qualified records into buffer
|
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
bytes memory buf = new bytes(500000);
uint256 index = 0;
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
| 7,994,010
|
// SPDX-License-Identifier: MIT
// 2nd part of the transition applier due to contract size restrictions
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/* Internal Imports */
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import {Transitions as tn} from "./libraries/Transitions.sol";
import "./libraries/ErrMsg.sol";
contract TransitionApplier2 {
uint256 public constant STAKING_SCALE_FACTOR = 1e12;
/**********************
* External Functions *
**********************/
/**
* @notice Apply an AggregateOrdersTransition.
*
* @param _transition The disputed transition.
* @param _strategyInfo The involved strategy from the previous transition.
* @return new strategy info after applying the disputed transition
*/
function applyAggregateOrdersTransition(
dt.AggregateOrdersTransition memory _transition,
dt.StrategyInfo memory _strategyInfo
) public pure returns (dt.StrategyInfo memory) {
uint256 npend = _strategyInfo.pending.length;
require(npend > 0, ErrMsg.REQ_NO_PEND);
dt.PendingStrategyInfo memory psi = _strategyInfo.pending[npend - 1];
require(_transition.buyAmount == psi.buyAmount, ErrMsg.REQ_BAD_AMOUNT);
require(_transition.sellShares == psi.sellShares, ErrMsg.REQ_BAD_SHARES);
uint256 minSharesFromBuy = (_transition.buyAmount * 1e18) / psi.maxSharePriceForBuy;
uint256 minAmountFromSell = (_transition.sellShares * psi.minSharePriceForSell) / 1e18;
require(_transition.minSharesFromBuy == minSharesFromBuy, ErrMsg.REQ_BAD_SHARES);
require(_transition.minAmountFromSell == minAmountFromSell, ErrMsg.REQ_BAD_AMOUNT);
_strategyInfo.nextAggregateId++;
return _strategyInfo;
}
/**
* @notice Apply a ExecutionResultTransition.
*
* @param _transition The disputed transition.
* @param _strategyInfo The involved strategy from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new strategy info after applying the disputed transition
*/
function applyExecutionResultTransition(
dt.ExecutionResultTransition memory _transition,
dt.StrategyInfo memory _strategyInfo,
dt.GlobalInfo memory _globalInfo
) public pure returns (dt.StrategyInfo memory, dt.GlobalInfo memory) {
uint256 idx;
bool found = false;
for (uint256 i = 0; i < _strategyInfo.pending.length; i++) {
if (_strategyInfo.pending[i].aggregateId == _transition.aggregateId) {
idx = i;
found = true;
break;
}
}
require(found, ErrMsg.REQ_BAD_AGGR);
if (_transition.success) {
_strategyInfo.pending[idx].sharesFromBuy = _transition.sharesFromBuy;
_strategyInfo.pending[idx].amountFromSell = _transition.amountFromSell;
}
_strategyInfo.pending[idx].executionSucceed = _transition.success;
_strategyInfo.pending[idx].unsettledBuyAmount = _strategyInfo.pending[idx].buyAmount;
_strategyInfo.pending[idx].unsettledSellShares = _strategyInfo.pending[idx].sellShares;
_strategyInfo.lastExecAggregateId = _transition.aggregateId;
return (_strategyInfo, _globalInfo);
}
/**
* @notice Apply a WithdrawProtocolFeeTransition.
*
* @param _transition The disputed transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new global info after applying the disputed transition
*/
function applyWithdrawProtocolFeeTransition(
dt.WithdrawProtocolFeeTransition memory _transition,
dt.GlobalInfo memory _globalInfo
) public pure returns (dt.GlobalInfo memory) {
_globalInfo.protoFees[_transition.assetId] -= _transition.amount;
return _globalInfo;
}
/**
* @notice Apply a TransferOperatorFeeTransition.
*
* @param _transition The disputed transition.
* @param _accountInfo The involved account from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new account info and global info after applying the disputed transition
*/
function applyTransferOperatorFeeTransition(
dt.TransferOperatorFeeTransition memory _transition,
dt.AccountInfo memory _accountInfo,
dt.GlobalInfo memory _globalInfo
) external pure returns (dt.AccountInfo memory, dt.GlobalInfo memory) {
require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT);
require(_accountInfo.account != address(0), ErrMsg.REQ_BAD_ACCT);
uint32 assetFeeLen = uint32(_globalInfo.opFees.assets.length);
if (assetFeeLen > 1) {
tn.adjustAccountIdleAssetEntries(_accountInfo, assetFeeLen - 1);
for (uint256 i = 1; i < assetFeeLen; i++) {
_accountInfo.idleAssets[i] += _globalInfo.opFees.assets[i];
_globalInfo.opFees.assets[i] = 0;
}
}
uint32 shareFeeLen = uint32(_globalInfo.opFees.shares.length);
if (shareFeeLen > 1) {
tn.adjustAccountShareEntries(_accountInfo, shareFeeLen - 1);
for (uint256 i = 1; i < shareFeeLen; i++) {
_accountInfo.shares[i] += _globalInfo.opFees.shares[i];
_globalInfo.opFees.shares[i] = 0;
}
}
return (_accountInfo, _globalInfo);
}
/**
* @notice Apply a UpdateEpochTransition.
*
* @param _transition The disputed transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new global info after applying the disputed transition
*/
function applyUpdateEpochTransition(dt.UpdateEpochTransition memory _transition, dt.GlobalInfo memory _globalInfo)
public
pure
returns (dt.GlobalInfo memory)
{
if (_transition.epoch >= _globalInfo.currEpoch) {
_globalInfo.currEpoch = _transition.epoch;
}
return _globalInfo;
}
/**
* @notice Apply a StakeTransition.
*
* @param _transition The disputed transition.
* @param _accountInfo The involved account from the previous transition.
* @param _stakingPoolInfo The involved staking pool from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new account, staking pool and global info after applying the disputed transition
*/
function applyStakeTransition(
dt.StakeTransition memory _transition,
dt.AccountInfo memory _accountInfo,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
)
external
pure
returns (
dt.AccountInfo memory,
dt.StakingPoolInfo memory,
dt.GlobalInfo memory
)
{
require(
ECDSA.recover(
ECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(
_transition.transitionType,
_transition.poolId,
_transition.shares,
_transition.fee,
_transition.timestamp
)
)
),
_transition.v,
_transition.r,
_transition.s
) == _accountInfo.account,
ErrMsg.REQ_BAD_SIG
);
require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT);
require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS);
require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP);
_accountInfo.timestamp = _transition.timestamp;
uint32 poolId = _transition.poolId;
uint256 feeInShares;
(bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee);
if (isCelr) {
_accountInfo.idleAssets[1] -= fee;
tn.updateOpFee(_globalInfo, true, 1, fee);
} else {
feeInShares = fee;
tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee);
}
uint256 addedShares = _transition.shares - feeInShares;
_updatePoolStates(_stakingPoolInfo, _globalInfo);
_adjustAccountStakedShareAndStakeEntries(_accountInfo, poolId);
_adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1));
if (addedShares > 0) {
uint256 addedStake = _getAdjustedStake(
_accountInfo.stakedShares[poolId] + addedShares,
_stakingPoolInfo.stakeAdjustmentFactor
) - _accountInfo.stakes[poolId];
_accountInfo.stakedShares[poolId] += addedShares;
_accountInfo.stakes[poolId] += addedStake;
_stakingPoolInfo.totalShares += addedShares;
_stakingPoolInfo.totalStakes += addedStake;
for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) {
_accountInfo.rewardDebts[poolId][rewardTokenId] +=
(addedStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) /
STAKING_SCALE_FACTOR;
}
}
tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId);
_accountInfo.shares[_stakingPoolInfo.strategyId] -= _transition.shares;
return (_accountInfo, _stakingPoolInfo, _globalInfo);
}
/**
* @notice Apply an UnstakeTransition.
*
* @param _transition The disputed transition.
* @param _accountInfo The involved account from the previous transition.
* @param _stakingPoolInfo The involved staking pool from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new account, staking pool and global info after applying the disputed transition
*/
function applyUnstakeTransition(
dt.UnstakeTransition memory _transition,
dt.AccountInfo memory _accountInfo,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
)
external
pure
returns (
dt.AccountInfo memory,
dt.StakingPoolInfo memory,
dt.GlobalInfo memory
)
{
require(
ECDSA.recover(
ECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(
_transition.transitionType,
_transition.poolId,
_transition.shares,
_transition.fee,
_transition.timestamp
)
)
),
_transition.v,
_transition.r,
_transition.s
) == _accountInfo.account,
ErrMsg.REQ_BAD_SIG
);
require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT);
require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS);
require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP);
_accountInfo.timestamp = _transition.timestamp;
uint32 poolId = _transition.poolId;
uint256 feeInShares;
(bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee);
if (isCelr) {
_accountInfo.idleAssets[1] -= fee;
tn.updateOpFee(_globalInfo, true, 1, fee);
} else {
feeInShares = fee;
tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee);
}
uint256 removedShares = _transition.shares;
_updatePoolStates(_stakingPoolInfo, _globalInfo);
require(_accountInfo.stakes.length > poolId, ErrMsg.REQ_BAD_AMOUNT);
_adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1));
uint256 originalStake = _accountInfo.stakes[poolId];
if (removedShares > 0) {
uint256 removedStake = _accountInfo.stakes[poolId] -
_getAdjustedStake(
_accountInfo.stakedShares[poolId] - removedShares,
_stakingPoolInfo.stakeAdjustmentFactor
);
_accountInfo.stakedShares[poolId] -= removedShares;
_accountInfo.stakes[poolId] -= removedStake;
_stakingPoolInfo.totalShares -= removedShares;
_stakingPoolInfo.totalStakes -= removedStake;
}
// Harvest
for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) {
// NOTE: Calculate pending reward using original stake to avoid rounding down twice
uint256 pendingReward = (originalStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) /
STAKING_SCALE_FACTOR -
_accountInfo.rewardDebts[poolId][rewardTokenId];
_accountInfo.rewardDebts[poolId][rewardTokenId] =
(_accountInfo.stakes[poolId] * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) /
STAKING_SCALE_FACTOR;
uint32 assetId = _stakingPoolInfo.rewardAssetIds[rewardTokenId];
_globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, assetId);
// Cap to available reward
if (pendingReward > _globalInfo.rewards[assetId]) {
pendingReward = _globalInfo.rewards[assetId];
}
_accountInfo.idleAssets[assetId] += pendingReward;
_globalInfo.rewards[assetId] -= pendingReward;
}
tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId);
_accountInfo.shares[_stakingPoolInfo.strategyId] += _transition.shares - feeInShares;
return (_accountInfo, _stakingPoolInfo, _globalInfo);
}
/**
* @notice Apply an AddPoolTransition.
*
* @param _transition The disputed transition.
* @param _stakingPoolInfo The involved staking pool from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new staking pool info after applying the disputed transition
*/
function applyAddPoolTransition(
dt.AddPoolTransition memory _transition,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
) external pure returns (dt.StakingPoolInfo memory) {
require(_transition.rewardAssetIds.length > 0, ErrMsg.REQ_BAD_LEN);
require(_transition.rewardAssetIds.length == _transition.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN);
require(_stakingPoolInfo.strategyId == 0, ErrMsg.REQ_BAD_SP);
require(_transition.startEpoch >= _globalInfo.currEpoch, ErrMsg.REQ_BAD_EPOCH);
_stakingPoolInfo.lastRewardEpoch = _transition.startEpoch;
_stakingPoolInfo.stakeAdjustmentFactor = _transition.stakeAdjustmentFactor;
_stakingPoolInfo.strategyId = _transition.strategyId;
_stakingPoolInfo.rewardAssetIds = new uint32[](_transition.rewardAssetIds.length);
for (uint256 i = 0; i < _transition.rewardAssetIds.length; i++) {
_stakingPoolInfo.rewardAssetIds[i] = _transition.rewardAssetIds[i];
}
_stakingPoolInfo.accumulatedRewardPerUnit = tn.adjustUint256Array(
_stakingPoolInfo.accumulatedRewardPerUnit,
uint32(_transition.rewardAssetIds.length - 1)
);
_stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length);
for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) {
_stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i];
}
return _stakingPoolInfo;
}
/**
* @notice Apply an UpdatePoolTransition.
*
* @param _transition The disputed transition.
* @param _stakingPoolInfo The involved staking pool from the previous transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new staking pool info after applying the disputed transition
*/
function applyUpdatePoolTransition(
dt.UpdatePoolTransition memory _transition,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
) external pure returns (dt.StakingPoolInfo memory) {
require(_transition.rewardPerEpoch.length == _stakingPoolInfo.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN);
require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP);
_updatePoolStates(_stakingPoolInfo, _globalInfo);
_stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length);
for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) {
_stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i];
}
return _stakingPoolInfo;
}
/**
* @notice Apply a DepositRewardTransition.
*
* @param _transition The disputed transition.
* @param _globalInfo The involved global info from the previous transition.
* @return new global info after applying the disputed transition
*/
function applyDepositRewardTransition(
dt.DepositRewardTransition memory _transition,
dt.GlobalInfo memory _globalInfo
) public pure returns (dt.GlobalInfo memory) {
_globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, _transition.assetId);
_globalInfo.rewards[_transition.assetId] += _transition.amount;
return _globalInfo;
}
/*********************
* Private Functions *
*********************/
function _updatePoolStates(dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo)
private
pure
{
if (_globalInfo.currEpoch > _stakingPoolInfo.lastRewardEpoch) {
uint256 totalStakes = _stakingPoolInfo.totalStakes;
if (totalStakes > 0) {
uint64 numEpochs = _globalInfo.currEpoch - _stakingPoolInfo.lastRewardEpoch;
for (
uint32 rewardTokenId = 0;
rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length;
rewardTokenId++
) {
uint256 pendingReward = numEpochs * _stakingPoolInfo.rewardPerEpoch[rewardTokenId];
_stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId] += ((pendingReward *
STAKING_SCALE_FACTOR) / totalStakes);
}
}
_stakingPoolInfo.lastRewardEpoch = _globalInfo.currEpoch;
}
}
/**
* Helper to expand the account array of staked shares and stakes if needed.
*/
function _adjustAccountStakedShareAndStakeEntries(dt.AccountInfo memory _accountInfo, uint32 poolId) private pure {
uint32 n = uint32(_accountInfo.stakedShares.length);
if (n <= poolId) {
uint256[] memory arr = new uint256[](poolId + 1);
for (uint32 i = 0; i < n; i++) {
arr[i] = _accountInfo.stakedShares[i];
}
for (uint32 i = n; i <= poolId; i++) {
arr[i] = 0;
}
_accountInfo.stakedShares = arr;
}
n = uint32(_accountInfo.stakes.length);
if (n <= poolId) {
uint256[] memory arr = new uint256[](poolId + 1);
for (uint32 i = 0; i < n; i++) {
arr[i] = _accountInfo.stakes[i];
}
for (uint32 i = n; i <= poolId; i++) {
arr[i] = 0;
}
_accountInfo.stakes = arr;
}
}
/**
* Helper to expand the 2D array of account reward debt entries per pool and reward token IDs.
*/
function _adjustAccountRewardDebtEntries(
dt.AccountInfo memory _accountInfo,
uint32 poolId,
uint32 rewardTokenId
) private pure {
uint32 n = uint32(_accountInfo.rewardDebts.length);
if (n <= poolId) {
uint256[][] memory rewardDebts = new uint256[][](poolId + 1);
for (uint32 i = 0; i < n; i++) {
rewardDebts[i] = _accountInfo.rewardDebts[i];
}
for (uint32 i = n; i < poolId; i++) {
rewardDebts[i] = new uint256[](0);
}
rewardDebts[poolId] = new uint256[](rewardTokenId + 1);
_accountInfo.rewardDebts = rewardDebts;
}
uint32 nRewardTokens = uint32(_accountInfo.rewardDebts[poolId].length);
if (nRewardTokens <= rewardTokenId) {
uint256[] memory debts = new uint256[](rewardTokenId + 1);
for (uint32 i = 0; i < nRewardTokens; i++) {
debts[i] = _accountInfo.rewardDebts[poolId][i];
}
for (uint32 i = nRewardTokens; i <= rewardTokenId; i++) {
debts[i] = 0;
}
_accountInfo.rewardDebts[poolId] = debts;
}
}
/**
* @notice Calculates the adjusted stake from staked shares.
* @param _stakedShares The staked shares
* @param _adjustmentFactor The adjustment factor, a value from (0, 1) * STAKING_SCALE_FACTOR
*/
function _getAdjustedStake(uint256 _stakedShares, uint256 _adjustmentFactor) private pure returns (uint256) {
return
((STAKING_SCALE_FACTOR - _adjustmentFactor) *
_stakedShares +
_sqrt(STAKING_SCALE_FACTOR * _adjustmentFactor * _stakedShares)) / STAKING_SCALE_FACTOR;
}
/**
* @notice Implements square root with Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method).
* @param _y The input
*/
function _sqrt(uint256 _y) private pure returns (uint256) {
uint256 z;
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;
}
return z;
}
}
|
Calculates the adjusted stake from staked shares. _stakedShares The staked shares _adjustmentFactor The adjustment factor, a value from (0, 1) STAKING_SCALE_FACTOR/
|
function _getAdjustedStake(uint256 _stakedShares, uint256 _adjustmentFactor) private pure returns (uint256) {
return
((STAKING_SCALE_FACTOR - _adjustmentFactor) *
_stakedShares +
_sqrt(STAKING_SCALE_FACTOR * _adjustmentFactor * _stakedShares)) / STAKING_SCALE_FACTOR;
}
| 12,924,596
|
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
pair = pairmanager.pairFor(tokenA, tokenB, _salt);
}
function createPair(address _tokenA, address _tokenB, bytes32 salt) external {
require(_tokenA != _tokenB ||
keccak256(abi.encodePacked(IERC20(_tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
"pair same token invalid");
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//create pair
(address token0, address token1, uint16 token0_id, uint16 token1_id) = _tokenA < _tokenB ? (_tokenA, _tokenB, tokenAID, tokenBID) : (_tokenB, _tokenA, tokenBID, tokenAID);
address pair = pairmanager.createPair(token0, token1, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
token0_id,
token1_id,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20, bytes32 salt) external {
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
erc20ID,
validatePairTokenAddress(pair),
pair);
}
function registerCreatePair(uint16 _tokenA, uint16 _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
(uint16 token0, uint16 token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
Operations.CreatePair memory op = Operations.CreatePair({
accountId: 0, //unknown at this point
tokenA: token0,
tokenB: token1,
tokenPair: _tokenPair,
pair: _pair
});
// pubData
bytes memory pubData = Operations.writeCreatePairPubdata(op);
addPriorityRequest(Operations.OpType.CreatePair, pubData);
emit OnchainCreatePair(token0, token1, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeNoticePeriodStarted() external override {}
/// @notice Notification that upgrade preparation status is activated
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradePreparationStarted() external override {
upgradePreparationActive = true;
upgradePreparationActivationTime = block.timestamp;
}
/// @notice Notification that upgrade canceled
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeCanceled() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeFinishes() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external view override returns (bool) {
return !exodusMode;
}
/// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// @dev _governanceAddress The address of Governance contract
/// @dev _verifierAddress The address of Verifier contract
/// @dev _pairManagerAddress the address of UniswapV2Factory contract
/// @dev _zkSyncCommitBlockAddress the address of ZkSyncCommitBlockAddress contract
/// @dev _genesisStateHash Genesis blocks (first block) state tree root hash
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress,
address _zkSyncCommitBlockAddress,
bytes32 _genesisStateHash
) = abi.decode(initializationParameters, (address, address, address, address, address, bytes32));
governance = Governance(_governanceAddress);
verifier = Verifier(_verifierAddress);
verifier_exit = VerifierExit(_verifierExitAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
// We need initial state hash because it is used in the commitment of the next block
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION);
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData);
priorityRequests[nextPriorityRequestId] = PriorityOperation({
hashedPubData: hashedPubData,
expirationBlock: expirationBlock,
opType: _opType
});
emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock));
totalOpenPriorityRequests++;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external nonReentrant {
require(totalBlocksCommitted == totalBlocksProven, "wq1"); // All the blocks must be proven
require(totalBlocksCommitted == totalBlocksExecuted, "w12"); // All the blocks must be executed
if (upgradeParameters.length != 0) {
StoredBlockInfo memory lastBlockInfo;
(lastBlockInfo) = abi.decode(upgradeParameters, (StoredBlockInfo));
storedBlockHashes[totalBlocksExecuted] = hashStoredBlockInfo(lastBlockInfo);
}
zkSyncCommitBlockAddress = address(0xcb4c185cC1bC048742D3b6AB760Efd2D3592c58f);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "L"); // exodus mode activated
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess == _depositsPubdata.length, "A");
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
function depositETH() external payable {
require(msg.value > 0, "1");
requireActive();
require(tokenIds[msg.sender] == 0, "da");
registerDeposit(0, SafeCast.toUint128(msg.value), msg.sender);
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
function depositERC20(IERC20 _token, uint104 _amount) external nonReentrant {
requireActive();
require(tokenIds[msg.sender] == 0, "db");
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
require(_token.balanceOf(address(this)) + _amount <= MAX_ERC20_TOKEN_BALANCE, "bgt");
} else {
// lpToken
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
// lpToken
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); //
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C1");
registerDeposit(lpTokenId, deposit_amount, msg.sender);
} else {
// token
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C2");
registerDeposit(tokenId, deposit_amount, msg.sender);
}
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _token Address of token, zero address is used for ETH
function getPendingBalance(address _address, address _token) public view returns (uint128) {
uint16 tokenId = 0;
if (_token != address(0)) {
tokenId = governance.validateTokenAddress(_token);
}
return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw;
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _tokenId token id, 0 is used for ETH
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function requestFullExit(uint32 _accountId, address _token) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
uint16 tokenId;
uint16 lpTokenId = tokenIds[_token];
if (_token == address(0)) {
tokenId = 0;
} else if (lpTokenId == 0) {
// This means it is not a pair address
// 非lpToken
tokenId = governance.validateTokenAddress(_token);
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
} else {
// lpToken
tokenId = lpTokenId;
}
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0, // unknown at this point
pairAccountId: 0
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE;
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function activateExodusMode() public returns (bool) {
bool trigger =
block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op =
Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount,
pairAccountId: 0
});
bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
fallback() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// 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;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
require(lockSlotOldValue == 0, "1B");
}
/**
* @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() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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, "14");
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, "v");
}
/**
* @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, "15");
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, "x");
}
/**
* @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, "y");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "12");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "aa");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 c = a * b;
require(c / a == b, "13");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "ad");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "16");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "17");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "18");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "19");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "1a");
return uint8(value);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
mstore(_bytes, sub(bytesLen, 32))
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title zkSync storage contract
/// @author Matter Labs
contract Storage {
/// @dev Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool internal upgradePreparationActive;
/// @dev Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradePreparationActivationTime;
/// @dev Verifier contract. Used to verify block proof
Verifier public verifier;
/// @dev Verifier contract. Used to verify exit proof
VerifierExit public verifier_exit;
/// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance public governance;
// NEW ADD
UniswapV2Factory internal pairmanager;
uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance
struct PendingBalance {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => PendingBalance) public pendingBalances;
/// @notice Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis)
uint32 public totalBlocksExecuted;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public performedExodus;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @Rollup block stored data
/// @member blockNumber Rollup block number
/// @member priorityOperations Number of priority operations processed
/// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify
/// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant
/// @member stateHash Root hash of the rollup state
/// @member commitment Verified input for the zkSync circuit
struct StoredBlockInfo {
uint32 blockNumber;
uint64 priorityOperations;
bytes32 pendingOnchainOperationsHash;
uint256 timestamp;
bytes32 stateHash;
bytes32 commitment;
}
/// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) public pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
/// @dev Stored hashed StoredBlockInfo for some block number
mapping(uint32 => bytes32) public storedBlockHashes;
/// @notice Total blocks proven.
uint32 public totalBlocksProven;
/// @notice Priority Operation container
/// @member hashedPubData Hashed priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
/// @member opType Priority operation type
struct PriorityOperation {
bytes20 hashedPubData;
uint64 expirationBlock;
Operations.OpType opType;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
// requestId -> PriorityOperation
mapping(uint64 => PriorityOperation) public priorityRequests;
// NEW ADD
address public zkSyncCommitBlockAddress;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
/// @author Stars Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev Bytes in one chunk
uint8 constant CHUNK_BYTES = 9;
/// @dev zkSync address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 511;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
/// @dev Max ERC20 token balance that is possible to deposit, suppose ((2**126) - 1)
uint128 internal constant MAX_ERC20_TOKEN_BALANCE = (2**126) - 1;
/// @dev Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 constant WITHDRAW_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
// NEW ADD
uint256 constant CREATE_PAIR_BYTES = 4 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 14 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 constant MASS_FULL_EXIT_PERIOD = 9 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 constant UPGRADE_NOTICE_PERIOD = 0 days;
/// @dev Timestamp - seconds since unix epoch
uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 168 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 constant INPUT_MASK = (~uint256(0) >> 3);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
/// @author Stars Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) {
require(_new_length <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _new_length, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
/// @author Matter Labs
/// @author Stars Labs
library Operations {
/// @notice zkSync circuit operation type
enum OpType {
Noop, //0
Deposit,
TransferToNew,
Withdraw,
Transfer,
FullExit, //5
ChangePubKey,
MiningMaintenance,
ClaimBonus,
CreatePair,
AddLiquidity,//10
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant OP_TYPE_BYTES = 1;
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @dev Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
// NEW ADD pairAccountId
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner, // owner
bytes4(0) // pairAccountId
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
// NEW ADD pairAccountId
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
// NEW ADD pairAccountId
uint32(0) // pairAccountId -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// Withdraw pubdata
struct Withdraw {
//uint8 opType; -- present in pubdata, ignored at serialization
// NEW ADD
uint32 accountId;
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
// NEW ADD
uint32 pairAccountId;
}
function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
// CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES;
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
// NEW ADD
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint16 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// CreatePair pubdata
// NEW ADD
struct CreatePair {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
// NEW ADD
uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
// NEW ADD
function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed)
{
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
// NEW ADD
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
OpType.CreatePair,
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
contract PairTokenManager {
/// @dev Max amount of pair tokens registered in the network.
/// This is computed by: 2048 - 512 = 1536
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 1536;
uint16 constant PAIR_TOKEN_START_ID = 512;
/// @dev Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @dev List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @dev List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @dev Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
// tokenId -> token
tokenAddresses[newPairTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @dev Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId < (PAIR_TOKEN_START_ID + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
require(tokenId >= PAIR_TOKEN_START_ID, "pms5");
return tokenId;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
function symbol() external pure returns (string memory);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireGovernor(msg.sender);
require(_token != address(0), "1e0");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
// tokenId -> token
tokenAddresses[newTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkVerifier, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyAggregatedBlockProof(
uint256[] memory _recursiveInput,
uint256[] memory _proof,
uint8[] memory _vkIndexes,
uint256[] memory _individual_vks_inputs,
uint256[16] memory _subproofs_limbs
) external view returns (bool) {
for (uint256 i = 0; i < _individual_vks_inputs.length; ++i) {
uint256 commitment = _individual_vks_inputs[i];
_individual_vks_inputs[i] = commitment & INPUT_MASK;
}
VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length));
return
verify_serialized_proof_with_recursion(
_recursiveInput,
_proof,
VK_TREE_ROOT,
VK_MAX_INDEX,
_vkIndexes,
_individual_vks_inputs,
_subproofs_limbs,
vk
);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkVerifierOld, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment =
sha256(abi.encodePacked(uint256(_rootHash) , _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _token_data,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory commit_data = concatBytes(_account_data, _token_data);
bytes32 commitment = sha256(commit_data);
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExitLp();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
}
pragma solidity ^0.7.0;
import './UniswapV2Pair.sol';
import "../IERC20.sol";
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract UniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() {}
function initialize(bytes calldata data) external {}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp2');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
address(this),
salt,
keccak256(bytecode)
))));
}
function createPair(address tokenA, address tokenB, bytes32 _salt) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB ||
keccak256(abi.encodePacked(IERC20(tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
UniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
UniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./PlonkCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifier is VerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x108678a23c44e8c0b590d3204fa7b710b4e74e590722c4d1f42cd1e6744bf4d3;
uint8 constant VK_MAX_INDEX = 3;
function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) {
if (_proofs == uint32(1)) { return getVkAggregated1(); }
else if (_proofs == uint32(4)) { return getVkAggregated4(); }
else if (_proofs == uint32(8)) { return getVkAggregated8(); }
else if (_proofs == uint32(18)) { return getVkAggregated18(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated4() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 8388608;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6,
0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089,
0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d,
0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b,
0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a,
0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43,
0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec,
0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb,
0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4,
0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df,
0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c,
0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a,
0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352,
0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated8() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f,
0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8,
0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2,
0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956,
0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9,
0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f,
0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64,
0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f,
0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015,
0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d,
0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2,
0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200,
0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a,
0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated18() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 33554432;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0d94d63997367c97a8ed16c17adaae39262b9af83acb9e003f94c217303dd160);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x0eab7c0217fbc357eb9e2622da6e5df9a99e5fa8dbaaf6b45a7136bbc49704c0,
0x00199f1c9e2ef5efbec5e3792cb6db0d6211e2da57e2e5a7cf91fb4037bd0013
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x020c5ecdbb37b9f99b131cdfd0fec8c5565985599093db03d85a9bcd75a8a186,
0x0be3b767834382739f1309adedb540ce5261b7038c168d32619a6e6333974b1b
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x092fc8636803f28250ac33b8ea688b37cf0718f83c82a1ce7bca70e7c8643b93,
0x10c907fcb34fb6e9d4e334428e8226ba84e5977a7dc1ada2509cc6cf445123ca
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1f66b77eaae034cf3646e0c32418a1dfecb3bf090cc271aad0d64ba327758b29,
0x2b8766fbe83c45b39e274998a000cf59e7332800025e7af711368c6b7ea11cd9
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x017336a15f6e61def3ec02f139a0972c4272e126ac40d49ed10d447db6857643,
0x22cc7cb62310a031acd86dd1a9ea18ee55e1b6a4fbf1c2d64ca9a7cc6458ed7a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x057992ff5d056557b795ab7e6964fab546fdcd8b5c1d3718e4f619e1091ef9a0,
0x026916de04486781c504fb054e0b3755dd4836b610973e0ca092b35810ed3698
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x252a53377145970214c9af5cd95c5fdd72e4d890b96d5ab31ef7736b2280aaa3,
0x2a1ccbea423d1a58325c4d0e5aa01a6a2a7c7fbaa61fb8f3669f720dfb4dfd4d
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x17da1e8102c91916c778e89d737bdc8a14f4dfcf14fc89896f921dfc81e98556,
0x1b9571239471b65bc5d4bcc3b1b3831bcc6986ad4d1417292dc3067ae632b796
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x242b5b8848746eb790629cf0853e256249d83cad8e189d474ed3a5c56b5a92be,
0x2ca4e4882f0d7408ba134458945a2dd7cbced64e735fd42c9204eaf8608c58cc
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x281ccb20cea7001ae0d3ef5deedc46db687f1493cd77631dc2c16275b96f677a,
0x24bede6b53ee4762939dbabb5947023d3ab31b00a1d14bcb6a5da69d7ce0d67e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x1e72df4c2223fb15e72862350f51994b7f381a829a00b21535b04e8c342c15e7,
0x22b7bb45c2e3b957952824beee1145bfcb5d2c575636266ad44032c1ae24e1ea
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x0059ea736670b355b3b6479db53d9b19727aa128514dee7d6c6788e80233452f,
0x24718998fb0ff667c66457f6558ff028352b2d55cb86a07a0c11fc3c2753df38
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x0bee5ac3770c7603b2ccbc9e10a0ceafa231e77dde3fd6b9d514958ae7c200e8,
0x11339336bbdafda32635c143b7bd0c4cdb7b7948489d75240c89ca2a440ef39c
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld {
function getVkExit() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1775efa56023e26c6298b2775481c0add1d64120dd242eb7e66cfebe43a8689d,
0x0adc370e09dc4bfcd73bf48ac1735363d2801dc50b903b950c2259cfec908422
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x1af5b8c0863df35aa93be8f75480bb8c4ad103993c05408856365dce2151cf72,
0x2aa95351d73b68ca33f9a8451cafeca8d9b66b9a5253b1196714d2d55f18c74e
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1a83514953af1d12f597ae8e159a69efdb4a19bc448f9bc3c100a5d27ab66467,
0x2e739d3240d665dba7ba612ca8548a2817ef3b26a5e31afd66121179860fb367
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x10fdde5088f9df8c2af09166c3e1d2aaf5bedaaf14095a81680285a7ea9a3207,
0x03cb4d015d2c8ab50e6e15c59aaeb0cc6f9dba3731c06513df9c3f77dcc7a75b
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x2e5f67efb618542c634c0cfef443d3ae7d57621fcc487e643d9174b1982ca106,
0x2a7761839026029cb215da80cfe536a4d6f7e993a749e21a0c430a455a6f6477
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x14ee91feb802eea1204e0b4faf96bd000d03e03a253e68f5e44e46880327eaa3,
0x1adfa909fe1008687d3867162b18aa895eed7a5dd10eeeee8d93876f9972f794
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x218b439287375a3f3cc2cad85805b47be7a0c5e8dd43c8c42305f7cb3d153fea,
0x1f94bb4131aee078b207615def18b0f2e94a966ce230fb1837df244657b06b60
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x0dc7db7aea2ef0f5d3b072faeaaee44bb1a79715e977bf87321d210140f4b443,
0x2ceb58346301f008a7553fe2851524e613d8060f309def3239494c2ac4722b99
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1d4ee99264d715b08b84286e6c979c47446b2cab86f6bb06d937e1d64814a322,
0x2cf40326362bbc1531e3d32e844e2986484ad74fac2b7e5c10bc5375f39dd271
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x20ffb570ec9e40ec87c2df09ec417e301d44db21323e2440134844a0d6aa18cf,
0x2d45d5f1e6fcfed9239d8f464c02a815498261b9a3edec9f4e1cd2058425aa96
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x28f43e5e320de920d29b0eabd68b6b93ea8beb12f35310b96b63ece18b8d99d3,
0x206324d60731845d125e4869c90ae15be2d160886b91bf3c316ac59af0688b6e
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkExitLp() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x15a418864253e30d92e0af8f44c45679ab52bb172c65bd1ca649bd352c55eb2f,
0x25d9ce8e852566a5a460653a634708f768f61da8bd3b986ac022cff0067011c2
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x2a7b4444d1b2eaad9dbd93c6bbae7d133fbaf0f71e3e769d35a379e63be37a97,
0x1420d2079a52ce83ee6b498e8a3fa498ec3bd48b92894a17996dfd23fbab90e3
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x17ad336a0139401277e75660ef40b0f07347f6d72d6b143e485953fc896cce9a,
0x227fcdd90c6dfc955c796e544e8bf0ea243e2ce0022e563716a5153260ceea6d
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x2c115c4700fc64f25ac77ba471b1dd5128c439163555331e1078cd6ee5627ba0,
0x2066980b107e6f2fa8160aaa88cb90113d2fd94ad62cd3366848c6746afa6acf
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x256677a67eca0e07a491e652e8e529e9d61e8833a7f90e8c2f1cdb6872260115,
0x0d1f62a5228c35e872a1146944c383d2d2d16dca4e8875bbf70f4d4b8834b6f5
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x1b041e5c782b57147cdfc17aad8b5881ebf895b75cf9d97f45c592f4dcfe640d,
0x01fbc948fd4701103a10bd5fee07fae81481e4f9ca90e36bd12c2ecfb1768b71
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x24d84ac5c820acc4ee6b6062092adc108c640a5750d837b28e5044bf992b45ef,
0x1faacb531160847bb4712202ee2b15a102084c24a2a8da1b687df5de8b2b6dd1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x28b25ca568d481180c47ff7f7beb6fa426c033c201a140c71cc5bbd090a69474,
0x0bc1b33a8d4a834cdb5b40ba275e2b33089120239abf4f9ffce983d1cfc9a85a
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x11012d815b96d6f9c95a50dd658f45d443472ee0432045f980f2c2745e4c3847,
0x235e2e22940391f97fcedda2690f3265ec813a964f95475f282c0f16602c1fb4
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2d7bb392ede616e3832f054a5ef35562522585563f1e978cbd3732069bcf4a24,
0x2b97bf5dd09f2765a35f1eeb2936767c20095d03666c1a5948544a74289a51df
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x0c3808600cf3d62ade4d2bb6cb856117f717ccd2a5cd2d549cdae1ad86bbb12b,
0x20827819d88e1dac7cd8f7cd1abce9eff8e9c936dbd305c364f0337298daa5b9
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod - 2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] X;
uint256[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return
G2Point(
[
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed
],
[
0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2) internal view {
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view {
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) {
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s) internal view {
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(
G1Point memory p,
Fr memory s,
G1Point memory dest
) internal view {
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length);
uint256 elements = p1.length;
uint256 inputSize = elements * 6;
uint256[] memory input = new uint256[](inputSize);
for (uint256 i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
contract Plonk4VerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK =
0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk)
internal
view
returns (bool valid, PairingsBn254.G1Point[2] memory part)
{
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(
recursive_proof_part[0],
PairingsBn254.P2(),
recursive_proof_part[1],
vk.g2_x
);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) =
reconstruct_recursive_public_input(
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] +
(subproofs_aggregated[1] << LIMB_WIDTH) +
(subproofs_aggregated[2] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[3] << (3 * LIMB_WIDTH)),
subproofs_aggregated[4] +
(subproofs_aggregated[5] << LIMB_WIDTH) +
(subproofs_aggregated[6] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[7] << (3 * LIMB_WIDTH))
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] +
(subproofs_aggregated[9] << LIMB_WIDTH) +
(subproofs_aggregated[10] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[11] << (3 * LIMB_WIDTH)),
subproofs_aggregated[12] +
(subproofs_aggregated[13] << LIMB_WIDTH) +
(subproofs_aggregated[14] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[15] << (3 * LIMB_WIDTH))
);
return (recursive_input, reconstructed_g1s);
}
}
contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (Proof memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid =
verify_recursive(
proof,
vk,
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
return valid;
}
}
contract Plonk4VerifierWithAccessToDNextOld {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH_OLD = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1;
struct VerificationKeyOld {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct ProofOld {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierStateOld {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain_old(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain_old(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) {
PartialVerifierStateOld memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld {
uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33;
function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (ProofOld memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
}
pragma solidity ^0.7.0;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
contract UniswapV2Pair is UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint256 amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint256 amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity ^0.7.0;
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'EdgeSwap V1';
string public constant symbol = 'Edge-V1';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity ^0.7.0;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
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;
}
}
}
pragma solidity ^0.7.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity ^0.7.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
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');
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
|
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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
| 72,175
|
./full_match/1/0xd9bF1095718405B4dF89f8E54EcC6D388aE2Be91/sources/contracts/danglydoodads.sol
|
setBaseURI for danglydoodads/
|
function setBaseURI(string memory _baseuri) external onlyOwner {
baseURI = _baseuri;
emit BatchMetadataUpdate(1, type(uint256).max);
}
| 9,645,172
|
./partial_match/4/0xc795c34b849E67c8013a5c8dA37A7c0Dc1Bfab4C/sources/GDAODelegator.sol
|
Remove minter minter minter/
|
function removeMinter(address minter)
external
returns (bool)
{
minter;
delegateToViewAndReturn();
}
| 8,666,919
|
./full_match/1/0xe64966e62B7E8De5260983D4ae89Ad75cC452a91/sources/BlockFlock_contract.sol
|
Return an empty array
|
function tokensOfOwner(address _owner) external view returns(uint[] memory ) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint[](0);
uint[] memory result = new uint[](tokenCount);
uint index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
| 4,924,378
|
./full_match/137/0x80b874961edF68c1ee7a097688bBB93FFe6C4db1/sources/src/contracts/BasicTypesTestContract.sol
|
array of strings write methods
|
function testStringDynamicArrayValue(string[] memory newValue) public {
stringDynamicArrayValue = newValue;
}
| 4,720,890
|
pragma solidity ^0.5.1;
import "./SnowflakeInterface.sol";
import "./IdentityRegistryInterface.sol";
import "./SafeMath.sol";
import "./IceGlobal.sol";
import "./IceSort.sol";
import "./IceFMSAdv.sol";
import "./IceFMS.sol";
/**
* @title Ice Protocol
* @author Harsh Rajat
* @notice Create Protocol Less File Storage, Grouping, Hassle free Encryption / Decryption and Stamping using Snowflake
* @dev This Contract forms File Storage / Stamping / Encryption part of Hydro Protocols
*/
contract Ice {
using SafeMath for uint;
using IceGlobal for IceGlobal.GlobalRecord;
using IceGlobal for IceGlobal.ItemOwner;
using IceGlobal for IceGlobal.Association;
using IceGlobal for IceGlobal.UserMeta;
using IceGlobal for mapping (uint => bool);
using IceGlobal for mapping (uint8 => IceGlobal.ItemOwner);
using IceGlobal for mapping (uint => mapping (uint => IceGlobal.Association));
using IceGlobal for uint;
using IceSort for mapping (uint => IceSort.SortOrder);
using IceSort for IceSort.SortOrder;
using IceFMS for IceFMS.File;
using IceFMS for mapping (uint => IceFMS.File);
using IceFMS for mapping (uint => mapping (uint => IceFMS.File));
using IceFMS for IceFMS.Group;
using IceFMS for mapping (uint => IceFMS.Group);
using IceFMSAdv for mapping (uint => IceGlobal.GlobalRecord);
using IceFMSAdv for mapping (uint => mapping(uint => IceGlobal.GlobalRecord));
/* ***************
* DEFINE STRUCTURES
*************** */
// Done in Libraries
/* ***************
* DEFINE VARIABLES
*************** */
/* for each item stored, ensure they can be retrieved publicly.
* globalIndex1 and globalIndex2 starts at 0 and will always increment
* given these indexes, any items can be retrieved.
*/
mapping (uint => mapping(uint => IceGlobal.Association)) globalItems;
uint public globalIndex1; // store the first index of association to retrieve files
uint public globalIndex2; // store the second index of association to retrieve files
/* for each user (EIN), look up the Transitioon State they have
* stored on a given index.
*/
mapping (uint => IceGlobal.UserMeta) public usermeta;
/* for each user (EIN), look up the file they have
* stored on a given index.
*/
mapping (uint => mapping(uint => IceFMS.File)) files;
mapping (uint => mapping(uint => IceSort.SortOrder)) public fileOrder; // Store round robin order of files
mapping (uint => uint) public fileCount; // store the maximum file count reached to provide looping functionality
/* for each user (EIN), look up the group they have
* stored on a given index. Default group 0 indicates
* root folder
*/
mapping (uint => mapping(uint => IceFMS.Group)) groups;
mapping (uint => mapping(uint => IceSort.SortOrder)) public groupOrder; // Store round robin order of group
mapping (uint => uint) public groupCount; // store the maximum group count reached to provide looping functionality
/* for each user (EIN), look up the incoming transfer request
* stored on a given index.
*/
mapping (uint => mapping(uint => IceGlobal.GlobalRecord)) public transfers;
mapping (uint => mapping(uint => IceSort.SortOrder)) public transferOrder; // Store round robin order of transfers
mapping (uint => uint) public transferCount; // store the maximum transfer request count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => IceGlobal.GlobalRecord)) public shares;
mapping (uint => mapping(uint => IceSort.SortOrder)) public shareOrder; // Store round robin order of sharing
mapping (uint => uint) public shareCount; // store the maximum shared items count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => IceGlobal.GlobalRecord)) public stampings;
mapping (uint => mapping(uint => IceSort.SortOrder)) public stampingOrder; // Store round robin order of stamping
mapping (uint => uint) public stampingCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => IceGlobal.GlobalRecord)) public stampingsReq;
mapping (uint => mapping(uint => IceSort.SortOrder)) public stampingReqOrder; // Store round robin order of stamping requests
mapping (uint => uint) public stampingReqCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), have a whitelist and blacklist
* association which can handle certain functions automatically.
*/
mapping (uint => mapping(uint => bool)) public whitelist;
mapping (uint => mapping(uint => bool)) public blacklist;
/* for referencing SnowFlake for Identity Registry (ERC-1484).
*/
SnowflakeInterface public snowflake;
IdentityRegistryInterface public identityRegistry;
/* ***************
* DEFINE EVENTS
*************** */
// When Item is hidden
event ItemHidden(uint EIN, uint fileIndex, bool status);
// When Item is Shared
event ItemShareChange(uint EIN, uint fileIndex);
// When File is created
event FileCreated(uint EIN, uint fileIndex, string fileName);
// When File is renamed
event FileRenamed(uint EIN, uint fileIndex, string fileName);
// When File is moved
event FileMoved(uint EIN, uint fileIndex, uint groupIndex, uint groupFileIndex);
// When File is deleted
event FileDeleted(uint EIN, uint fileIndex);
// When Group is created
event GroupCreated(uint EIN, uint groupIndex, string groupName);
// When Group is renamed
event GroupRenamed(uint EIN, uint groupIndex, string groupName);
// When Group Status is changed
event GroupDeleted(uint EIN, uint groupIndex, uint groupReplacedIndex);
// When Sharing is completed
event SharingCompleted(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Sharing is rejected
event SharingRejected(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Sharing is removed
event SharingRemoved(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Stamping is initiated
event StampingInitiated(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Stamping is accepted by the recipient
event StampingAccepted(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Stamping is rejected by the recipient
event StampingRejected(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Stamping is revoked by the owner
event StampingRevoked(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Transfer is initiated
event FileTransferInitiated(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Transfer is accepted by the recipient
event FileTransferAccepted(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Transfer is rejected by the recipient
event FileTransferRejected(uint EIN, uint index1, uint index2, uint recipientEIN);
// When Transfer is revoked by the owner
event FileTransferRevoked(uint EIN, uint index1, uint index2, uint recipientEIN);
// When whitelist is updated
event AddedToWhitelist(uint EIN, uint recipientEIN);
event RemovedFromWhitelist(uint EIN, uint recipientEIN);
// When blacklist is updated
event AddedToBlacklist(uint EIN, uint recipientEIN);
event RemovedFromBlacklist(uint EIN, uint recipientEIN);
/* ***************
* DEFINE CONSTRUCTORS AND RELATED FUNCTIONS
*************** */
//CONSTRUCTOR / FUNCTIONS
constructor (address snowflakeAddress) public {
snowflake = SnowflakeInterface(snowflakeAddress);
identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
}
// constructor () public {
// }
// //function callConstructor(address snowflakeAddress) public returns (SnowflakeInterface snowflake,IdentityRegistryInterface identityRegistry){
// function callConstructor(address snowflakeAddress) public returns (SnowflakeInterface ,IdentityRegistryInterface){
// //snowflake = _snowflake;
// //identityRegistry = _IdentityRegistryInterface;
// snowflake = SnowflakeInterface(snowflakeAddress);
// identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
// return(snowflake,identityRegistry);
// }
/* ***************
* DEFINE CONTRACT FUNCTIONS
*************** */
// 1. GLOBAL ITEMS FUNCTIONS
/**
* @dev Function to get global items info from the entire File Management System of Ice
* @param _index1 is the first index of item
* @param _index2 is the second index of item
* @return ownerEIN is the EIN of the user who owns the item
* @return itemRecord is the record of that item in relation to the individual user
* @return isFile indicates if the item is file or group
* @return isHidden indicates if the item is hidder or visible
* @return deleted indicates if the item is already deleted from the individual user perspective
* @return sharedToCount is the count of sharing the item has
*/
function getGlobalItems(
uint _index1,
uint _index2
)
external view
returns (
uint ownerEIN,
uint itemRecord,
bool isFile,
bool isHidden,
bool deleted,
uint sharedToCount
) {
// Logic
(ownerEIN, itemRecord, isFile, isHidden, deleted, sharedToCount) = globalItems[_index1][_index2].getGlobalItems();
}
/**
* @dev Function to get global items stamping info from the entire File Management System of Ice
* @param _index1 is the first index of item
* @param _index2 is the second index of item
* @return stampingRecipient is the EIN of the recipient for whom stamping is requested / denied / completed
* @return stampingRecipientIndex is the item index mapped in the mapping of stampingsReq of that recipient
* @return stampingInitiated either returns 0 (false) or timestamp when the stamping was initiated
* @return stampingCompleted either returns 0 (false) or timestamp when the stamping was completed
* @return stampingRejected indicates if the stamping was rejected by the recipient
*/
function getGlobalItemsStampingInfo(
uint _index1,
uint _index2
)
external view
returns (
uint stampingRecipient,
uint stampingRecipientIndex,
uint32 stampingInitiated,
uint32 stampingCompleted,
bool stampingRejected
) {
// Logic
(
stampingRecipient,
stampingRecipientIndex,
stampingInitiated,
stampingCompleted,
stampingRejected
) = globalItems[_index1][_index2].getGlobalItemsStampingInfo();
}
/**
* @dev Function to get global items
* @param _index1 is the first index of item
* @param _index2 is the second index of item
* @param _isHidden is the flag to hide that item or not
*/
function hideGlobalItem(
uint _index1,
uint _index2,
bool _isHidden
)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
globalItems[_index1][_index2].condItemOwner(ein);
// Logic
globalItems[_index1][_index2].isHidden = _isHidden;
// Trigger Event
emit ItemHidden(ein, globalItems[_index1][_index2].ownerInfo.EIN, _isHidden);
}
/**
* @dev Function to get info of mapping to user for a specific global item
* @param _index1 is the first index of global item
* @param _index2 is the second index of global item
* @param _ofType indicates the type. 0 - shares, 1 - stampings
* @param _mappedIndex is the index
* @return mappedToEIN is the user (EIN)
* @return atIndex is the specific index in question, only returns on shares types
* @return timestamp is the time when the file was stamped by the EIN, only returns on stamping types
*/
function getGlobalItemsMapping(
uint _index1,
uint _index2,
uint8 _ofType,
uint8 _mappedIndex
)
external view
returns (
uint mappedToEIN,
uint atIndex
) {
// Allocalte based on type.
if (_ofType == uint8(IceGlobal.AsscProp.sharedTo)) {
mappedToEIN = globalItems[_index1][_index2].sharedTo[_mappedIndex].EIN;
atIndex = globalItems[_index1][_index2].sharedTo[_mappedIndex].index;
}
else if (_ofType == uint8(IceGlobal.AsscProp.stampedTo)) {
mappedToEIN = globalItems[_index1][_index2].stampingRecipient.EIN;
atIndex = globalItems[_index1][_index2].stampingRecipient.index;
}
}
// 2. FILE FUNCTIONS
/**
* @dev Function to get the desired amount of files indexes (max 20 at times) of an EIN, the 0 indicates
* @param _ein is the EIN of the user
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
* @return fileIndexes is the array of file indexes for the specified users
*/
function getFileIndexes(
uint _ein,
uint _seedPointer,
uint16 _limit,
bool _asc
)
external view
returns (uint[20] memory fileIndexes) {
fileIndexes = fileOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
}
/**
* @dev Function to get file info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
* @return protocol is the protocol used for storing that file (for example: 1 is IPFS, etc, etc). Used to fetch file from JS Library
* @return protocolMeta contains the additional essential infomation about the protocol if any
* @return name is the name of the file along with the extension
* @return hash1 is the
*
*/
function getFileInfo(
uint _ein,
uint _fileIndex
)
external view
returns (
uint8 protocol,
bytes memory protocolMeta,
string memory fileName,
bytes32 fileHash,
bytes22 hashExtraInfo,
uint8 hashFunction,
uint8 hashSize,
bool encryptedStatus
) {
// Logic
(protocol, protocolMeta, fileName, fileHash, hashExtraInfo, hashFunction, hashSize, encryptedStatus) = files[_ein][_fileIndex].getFileInfo();
}
/**
* @dev Function to get file info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFileOtherInfo(uint _ein, uint _fileIndex)
external view
returns (uint32 timestamp, uint associatedGroupIndex, uint associatedGroupFileIndex) {
// Logic
(timestamp, associatedGroupIndex, associatedGroupFileIndex) = files[_ein][_fileIndex].getFileOtherInfo();
}
/**
* @dev Function to get file tranfer info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFileTransferInfo(uint _ein, uint _fileIndex)
external view
returns (uint transCount, uint transEIN, uint transIndex, bool forTrans) {
// Logic
(transCount, transEIN, transIndex, forTrans) = files[_ein][_fileIndex].getFileTransferInfo();
}
/**
* @dev Function to get file tranfer owner info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
* @param _transferCount is index to poll
*/
function getFileTransferOwners(uint _ein, uint _fileIndex, uint _transferCount)
external view
returns (uint recipientEIN) {
recipientEIN = files[_ein][_fileIndex].getFileTransferOwners(_transferCount);
}
// /**
// * @dev Function to add File
// * @param _protocol is the protocol used
// * @param _protocolMeta is the metadata used by the protocol if any
// * @param _name is the name of the file
// * @param _hash1 is the first split hash of the stored file
// * @param _hash2 is the second split hash of the stored file
// * @param _encrypted defines if the file is encrypted or not
// * @param _encryptedHash defines the encrypted public key password for the sender address
// * @param _groupIndex defines the index of the group of file
// */
function addFile(
uint8 _op,
uint8 _protocol,
bytes memory _protocolMeta,
bytes32 _name,
bytes32 _hash,
bytes22 _hashExtraInfo,
uint8 _hashFunction,
uint8 _hashSize,
bool _encrypted,
bytes32 _encryptedHash,
uint _groupIndex
)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check constraints
_groupIndex.condValidItem(groupCount[ein]);
// To fill with global index if need be
IceGlobal.GlobalRecord memory rec;
// Create File
uint nextIndex;
// OP 0 - Normal | 1 - Avatar
if (_op == 0) {
// Reserve Global Index
(globalIndex1, globalIndex2) = IceGlobal.reserveGlobalItemSlot(globalIndex1, globalIndex2);
// Create the record
rec = IceGlobal.GlobalRecord(globalIndex1, globalIndex2);
// Create File Next Index
nextIndex = fileCount[ein] + 1;
// Add to globalItems
globalItems.addItemToGlobalItems(rec.i1, rec.i2, ein, nextIndex, true, false, 0);
}
// Finally create the file object (EIN)
files[ein][nextIndex].createFileObject(
_protocolMeta,
_groupIndex,
groups[ein][_groupIndex].groupFilesCount
);
// Assign global item record
files[ein][nextIndex].rec = rec;
// Also create meta object
files[ein][nextIndex].createFileMetaObject(
_protocol,
_name,
_hash,
_hashExtraInfo,
_hashFunction,
_hashSize,
_encrypted
);
// OP 0 - Normal | 1 - Avatar
if (_op == 0) {
fileCount[ein] = files[ein][nextIndex].writeFile(
groups[ein][_groupIndex],
_groupIndex,
fileOrder[ein],
fileCount[ein],
nextIndex,
ein,
_encryptedHash
);
}
else if (_op == 1) {
usermeta[ein].hasAvatar = true;
}
// Trigger Event
emit FileCreated(ein, nextIndex, IceFMS.bytes32ToString(_name));
}
// /**
// * @dev Function to change File Name
// * @param _fileIndex is the index where file is stored
// * @param _name is the name of stored file
// */
function changeFileName(
uint _fileIndex,
bytes32 _name
)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
files[ein][_fileIndex].fileMeta.name = _name;
// Trigger Event
emit FileRenamed(ein, _fileIndex, IceFMS.bytes32ToString(_name));
}
// /**
// * @dev Function to move file to another group
// * @param _fileIndex is the index where file is stored
// * @param _newGroupIndex is the index of the new group where file has to be moved
// */
function moveFileToGroup(
uint _fileIndex,
uint _newGroupIndex
)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
uint groupFileIndex = files[ein][_fileIndex].moveFileToGroup(_fileIndex, groups[ein], groupOrder[ein], _newGroupIndex, globalItems);
// Trigger Event
emit FileMoved(ein, _fileIndex, _newGroupIndex, groupFileIndex);
}
// /**
// * @dev Function to delete file of the owner
// * @param _fileIndex is the index where file is stored
// */
function deleteFile(uint _fileIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Delegate the call
_deleteFileAnyOwner(ein, _fileIndex);
// Trigger Event
emit FileDeleted(ein, _fileIndex);
}
// /**
// * @dev Function to delete file of any EIN
// * @param _ein is the owner EIN
// * @param _fileIndex is the index where file is stored
// */
function _deleteFileAnyOwner(
uint _ein,
uint _fileIndex
)
internal {
// Logic
files[_ein].deleteFile(
_ein,
_fileIndex,
files[_ein][_fileIndex].rec.getGlobalItemViaRecord(globalItems),
fileOrder[_ein],
fileCount,
groups[_ein][files[_ein][_fileIndex].associatedGroupIndex],
groupOrder[_ein][files[_ein][_fileIndex].associatedGroupIndex],
shares,
shareOrder,
shareCount
);
}
// 3. GROUP FILES FUNCTIONS
/**
* @dev Function to get all the files of an EIN associated with a group
* @param _ein is the owner EIN
* @param _groupIndex is the index where group is stored
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
*/
function getGroupFileIndexes(
uint _ein,
uint _groupIndex,
uint _seedPointer,
uint16 _limit,
bool _asc
)
external view
returns (uint[20] memory groupFileIndexes) {
return groups[_ein][_groupIndex].groupFilesOrder.getIndexes(_seedPointer, _limit, _asc);
}
// 4. GROUP FUNCTIONS
/**
* @dev Function to return group info for an EIN
* @param _ein the EIN of the user
* @param _groupIndex the index of the group
* @return index is the index of the group
* @return name is the name associated with the group
*/
function getGroup(
uint _ein,
uint _groupIndex
)
external view
returns (
uint index,
string memory name
) {
// Logic
(index, name) = groups[_ein][_groupIndex].getGroup(_groupIndex, groupCount[_ein]);
}
/**
* @dev Function to return group indexes used to retrieve info about group
* @param _ein the EIN of the user
* @param _seedPointer is the pointer (index) of the order mapping
* @param _limit is the number of indexes to return, capped at 20
* @param _asc is the order of group indexes in Ascending or Descending order
* @return groupIndexes the indexes of the groups associated with the ein in the preferred order
*/
function getGroupIndexes(uint _ein, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory groupIndexes) {
groupIndexes = groupOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
}
/**
* @dev Function to create a new Group for the user
* @param _groupName describes the name of the group
*/
function createGroup(string memory _groupName)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
uint nextGroupIndex;
(globalIndex1, globalIndex2, nextGroupIndex) = groups[ein].createGroup(
ein,
_groupName,
groupOrder[ein],
groupCount,
globalItems,
globalIndex1,
globalIndex2
);
// Trigger Event
emit GroupCreated(ein, nextGroupIndex, _groupName);
}
/**
* @dev Function to rename an existing Group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
* @param _groupName describes the new name of the group
*/
function renameGroup(
uint _groupIndex,
string calldata _groupName
)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
groups[ein][_groupIndex].renameGroup(_groupIndex, groupCount[ein], _groupName);
// Trigger Event
emit GroupRenamed(ein, _groupIndex, _groupName);
}
/**
* @dev Function to delete an existing group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
*/
function deleteGroup(uint _groupIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
uint currentGroupIndex = groups[ein].deleteGroup(
ein,
_groupIndex,
groupOrder[ein],
groupCount,
shares,
shareOrder,
shareCount,
globalItems
);
// Trigger Event
emit GroupDeleted(ein, _groupIndex, currentGroupIndex);
}
// 4. SHARING FUNCTIONS
/**
* @dev Function to share an item to other users, always called by owner of the Item
* @param _toEINs are the array of EINs which the item should be shared to
* @param _itemIndex is the index of the item to be shared to
* @param _isFile indicates if the item is file or group
*/
function shareItemToEINs(uint[] calldata _toEINs, uint _itemIndex, bool _isFile)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check if item is file or group and accordingly check if Item is valid & Logic
if (_isFile == true) {
_itemIndex.condValidItem(fileCount[ein]);
shares.shareItemToEINs(globalItems, shareOrder, shareCount, blacklist, files[ein][_itemIndex].rec, ein, _toEINs);
}
else {
_itemIndex.condValidItem(groupCount[ein]);
shares.shareItemToEINs(globalItems, shareOrder, shareCount, blacklist, groups[ein][_itemIndex].rec, ein, _toEINs);
}
}
/**
* @dev Function to remove a shared item from the multiple user's mapping, always called by owner of the Item
* @param _fromEINs are the EINs to which the item should be removed from sharing
* @param _itemIndex is the index of the item on the owner's mapping
* @param _isFile indicates if the item is file or group
*/
function removeShareFromEINs(
uint[] memory _fromEINs,
uint _itemIndex,
bool _isFile
)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check if item is file or group and accordingly check if Item is valid & Logic
IceGlobal.GlobalRecord memory rec;
if (_isFile == true) {
_itemIndex.condValidItem(fileCount[ein]);
rec = files[ein][_itemIndex].rec;
}
else {
_itemIndex.condValidItem(groupCount[ein]);
rec = groups[ein][_itemIndex].rec;
}
shares.removeShareFromEINs(
ein,
_fromEINs,
globalItems[rec.i1][rec.i2],
shareOrder,
shareCount
);
}
/**
* @dev Function to remove shared item by the user to whom the item is shared
* @param _itemIndex is the index of the item in shares
*/
function removeSharingItemBySharee(uint _itemIndex)
external {
// Logic
uint shareeEIN = identityRegistry.getEIN(msg.sender);
IceGlobal.Association storage globalItem = shares[shareeEIN][_itemIndex].getGlobalItemViaRecord(globalItems);
shares[shareeEIN].removeSharingItemBySharee(
shareeEIN,
globalItem,
shareOrder[shareeEIN],
shareCount
);
}
// 5. STAMPING FUNCTIONS
/**
* @dev Function to initiate stamping of an item by the owner of that item
* @param _itemIndex is the index of the item (File or Group)
* @param _isFile indicates if the item is File or Group
* @param _recipientEIN is the recipient EIN of the user who has to stamp the item
*/
function initiateStampingOfItem(
uint _itemIndex,
bool _isFile,
uint _recipientEIN
)
external {
// Logic
if (_isFile) {
stampingsReq[_recipientEIN].initiateStampingOfItem(
stampingReqOrder[_recipientEIN],
stampingReqCount,
identityRegistry.getEIN(msg.sender),
_recipientEIN,
_itemIndex,
fileCount[identityRegistry.getEIN(msg.sender)],
files[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.getGlobalItemViaRecord(globalItems),
files[identityRegistry.getEIN(msg.sender)][_itemIndex].rec,
blacklist,
identityRegistry
);
// Trigger Event
emit StampingInitiated(
identityRegistry.getEIN(msg.sender),
files[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.i1,
files[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.i2,
_recipientEIN
);
}
else {
stampingsReq[_recipientEIN].initiateStampingOfItem(
stampingReqOrder[_recipientEIN],
stampingReqCount,
identityRegistry.getEIN(msg.sender),
_recipientEIN,
_itemIndex,
groupCount[identityRegistry.getEIN(msg.sender)],
groups[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.getGlobalItemViaRecord(globalItems),
groups[identityRegistry.getEIN(msg.sender)][_itemIndex].rec,
blacklist,
identityRegistry
);
// Trigger Event
emit StampingInitiated(
identityRegistry.getEIN(msg.sender),
groups[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.i1,
groups[identityRegistry.getEIN(msg.sender)][_itemIndex].rec.i2,
_recipientEIN
);
}
}
/**
* @dev Function to accept stamping of an item by the intended recipient
* @param _stampingReqIndex is the index of the item present in the Stamping Requests mapping of the recipient
*/
function acceptStamping(
uint _stampingReqIndex
)
external {
// Get user EIN
uint recipientEIN = identityRegistry.getEIN(msg.sender);
// Logic
stampings[recipientEIN].acceptStamping(
stampingOrder[recipientEIN],
stampingCount,
stampingsReq[recipientEIN],
stampingReqOrder[recipientEIN],
stampingReqCount,
stampingsReq[recipientEIN][_stampingReqIndex].getGlobalItemViaRecord(globalItems),
recipientEIN,
_stampingReqIndex
);
// Trigger Event
emit StampingAccepted(
identityRegistry.getEIN(msg.sender),
stampingsReq[recipientEIN][_stampingReqIndex].i1,
stampingsReq[recipientEIN][_stampingReqIndex].i2,
recipientEIN
);
}
/**
* @dev Function to revoke stamping of an item only by the owner
* @param _ownerItemIndex is the index of the item (File or Group) in relation to the owner of the item
* @param _isFile indicates if the item is File or Group
*/
function revokeStamping(
uint _ownerItemIndex,
bool _isFile
)
external {
// Get user EIN
uint ownerEIN = identityRegistry.getEIN(msg.sender);
// Get recipient info
IceGlobal.Association storage globalItem = files[ownerEIN][_ownerItemIndex].rec.getGlobalItemViaRecord(globalItems);
if (_isFile == false) {
globalItem = groups[ownerEIN][_ownerItemIndex].rec.getGlobalItemViaRecord(globalItems);
}
uint recipientEIN = globalItem.stampingRecipient.EIN;
uint recipientItemIndex = globalItem.stampingRecipient.index;
// Trigger Event
emit StampingRevoked(
ownerEIN,
stampingsReq[recipientEIN][recipientItemIndex].i1,
stampingsReq[recipientEIN][recipientItemIndex].i2,
recipientEIN
);
// Logic
stampingsReq[recipientEIN].cancelStamping(
stampingReqOrder[recipientEIN],
stampingReqCount,
recipientEIN,
recipientItemIndex,
globalItem
);
}
/**
* @dev Function to reject stamping of an item only by the recipient
* @param _recipientItemIndex is the index of the item present in the Stamping Requests mapping of the recipient
*/
function rejectStamping(
uint _recipientItemIndex
)
external {
// Get user EIN
uint recipientEIN = identityRegistry.getEIN(msg.sender);
// Logic
IceGlobal.Association storage globalItem = stampingsReq[recipientEIN][_recipientItemIndex].getGlobalItemViaRecord(globalItems);
// Trigger Event
emit StampingRejected(
globalItem.ownerInfo.EIN,
stampingsReq[recipientEIN][_recipientItemIndex].i1,
stampingsReq[recipientEIN][_recipientItemIndex].i2,
recipientEIN
);
// Reject Stamping
stampingsReq[recipientEIN].cancelStamping(
stampingReqOrder[recipientEIN],
stampingReqCount,
recipientEIN,
_recipientItemIndex,
globalItem
);
// Map the rejected flag for the owner
globalItem.stampingRejected = true;
}
// 6. TRANSFER FILE FUNCTIONS
/**
* @dev Function to intiate file transfer to another EIN(user)
* @param _fileIndex is the index of file for the original user's EIN
* @param _transfereeEIN is the recipient user's EIN
*/
function initiateFileTransfer(
uint _fileIndex,
uint _transfereeEIN
)
external {
// Get user EIN
uint transfererEIN = identityRegistry.getEIN(msg.sender);
// Check Restrictions
IceFMS.doInitiateFileTransferChecks(
files,
transfererEIN,
_transfereeEIN,
_fileIndex,
fileCount,
groups,
blacklist,
globalItems,
identityRegistry
);
// Check and change flow if white listed
if (whitelist[_transfereeEIN][transfererEIN] == true) {
// Directly transfer file, 0 is always root group
_doDirectFileTransfer(transfererEIN, _transfereeEIN, _fileIndex, 0);
}
else {
// Trigger Event
emit FileTransferInitiated(transfererEIN, files[transfererEIN][_fileIndex].rec.i1, files[transfererEIN][_fileIndex].rec.i2, _transfereeEIN);
// Request based file Transfers
files[transfererEIN][_fileIndex].doPermissionedFileTransfer(
_transfereeEIN,
transfers[_transfereeEIN],
transferOrder[_transfereeEIN],
transferCount,
globalItems
);
}
}
/**
* @dev Private Function to do file transfer from previous (current) owner to new owner
* @param _transfererEIN is the previous(current) owner EIN
* @param _transfereeEIN is the EIN of the user to whom the file needs to be transferred
* @param _fileIndex is the index where file is stored in the owner
* @param _toRecipientGroup is the index of the group where the file is suppose to be for the recipient
*/
function _doDirectFileTransfer(
uint _transfererEIN,
uint _transfereeEIN,
uint _fileIndex,
uint _toRecipientGroup
)
internal {
// Trigger Event
emit FileTransferAccepted(_transfererEIN, files[_transfererEIN][_fileIndex].rec.i1, files[_transfererEIN][_fileIndex].rec.i2, _transfereeEIN);
// Logic
uint nextTransfereeIndex = files.doFileTransferPart1 (
_transfererEIN,
_transfereeEIN,
_fileIndex,
fileOrder,
fileCount
);
files.doFileTransferPart2 (
_transfereeEIN,
_fileIndex,
_toRecipientGroup,
groupCount[_transfereeEIN],
nextTransfereeIndex,
groups,
globalItems
);
// Delete File
_deleteFileAnyOwner(_transfererEIN, _fileIndex);
}
/**
* @dev Function to accept file transfer from a user
* @param _atRecipientTransferIndex is the file mapping stored no the recipient transfers mapping
* @param _toRecipientGroup is the index of the group where the file is suppose to be for the recipient
*/
function acceptFileTransfer(
uint _atRecipientTransferIndex,
uint _toRecipientGroup
)
external {
// Get user EIN | Transferee initiates this
uint transfereeEIN = identityRegistry.getEIN(msg.sender);
// Get owner info
IceGlobal.ItemOwner memory ownerInfo = transfers[transfereeEIN][_atRecipientTransferIndex].getGlobalItemViaRecord(globalItems).ownerInfo;
uint transfererEIN = ownerInfo.EIN;
uint fileIndex = ownerInfo.index;
// Accept File Transfer Part 1
files.acceptFileTransferPart1(
transfererEIN,
transfereeEIN,
fileIndex
);
// Do file transfer
_doDirectFileTransfer(transfererEIN, transfereeEIN, fileIndex, _toRecipientGroup);
// Accept File Transfer Part 2
files.acceptFileTransferPart2(
transfereeEIN,
_atRecipientTransferIndex,
transfers[transfereeEIN],
transferOrder[transfereeEIN],
transferCount,
globalItems
);
}
/**
* @dev Function to revoke file transfer inititated by the current owner of that file
* @param _transfereeEIN is the EIN of the user to whom the file needs to be transferred
* @param _fileIndex is the index where file is stored
*/
function revokeFileTransfer(
uint _transfereeEIN,
uint _fileIndex
)
external {
// Get user EIN | Transferer initiates this
uint transfererEIN = identityRegistry.getEIN(msg.sender);
// Logic
files.cancelFileTransfer(
transfererEIN,
_transfereeEIN,
_fileIndex,
transfers[_transfereeEIN],
transferOrder[_transfereeEIN],
transferCount,
globalItems
);
// Trigger Event
emit FileTransferRevoked(transfererEIN, files[transfererEIN][_fileIndex].rec.i1, files[transfererEIN][_fileIndex].rec.i2, _transfereeEIN);
}
/**
* @dev Function to revoke file transfer inititated by the current owner of that file
* @param _atRecipientTransferIndex is the file mapping stored no the recipient transfers mapping
*/
function rejectFileTransfer(
uint _atRecipientTransferIndex
)
external
returns (
uint, uint
){
// Get user EIN | Transferee initiates this
uint transfereeEIN = identityRegistry.getEIN(msg.sender);
// Get owner info
IceGlobal.ItemOwner memory ownerInfo = transfers[transfereeEIN][_atRecipientTransferIndex].getGlobalItemViaRecord(globalItems).ownerInfo;
uint transfererEIN = ownerInfo.EIN;
uint fileIndex = ownerInfo.index;
// Logic
files.cancelFileTransfer(
transfererEIN,
transfereeEIN,
fileIndex,
transfers[transfereeEIN],
transferOrder[transfereeEIN],
transferCount,
globalItems
);
// Trigger Event
emit FileTransferRejected(transfererEIN, files[transfererEIN][fileIndex].rec.i1, files[transfererEIN][fileIndex].rec.i2, transfereeEIN);
}
// 7. WHITELIST / BLACKLIST FUNCTIONS
/**
* @dev Add a non-owner user to whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToWhitelist(uint _nonOwnerEIN)
external {
// Logic
uint ein = identityRegistry.getEIN(msg.sender);
whitelist[ein].addToWhitelist(_nonOwnerEIN, blacklist[ein]);
// Trigger Event
emit AddedToWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromWhitelist(uint _nonOwnerEIN)
external {
// Logic
uint ein = identityRegistry.getEIN(msg.sender);
whitelist[ein].removeFromWhitelist(_nonOwnerEIN, blacklist[ein]);
// Trigger Event
emit RemovedFromWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user to blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToBlacklist(uint _nonOwnerEIN)
external {
// Logic
uint ein = identityRegistry.getEIN(msg.sender);
blacklist[ein].addToBlacklist(_nonOwnerEIN, whitelist[ein]);
// Trigger Event
emit AddedToBlacklist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromBlacklist(uint _nonOwnerEIN)
external {
// Logic
uint ein = identityRegistry.getEIN(msg.sender);
blacklist[ein].removeFromBlacklist(_nonOwnerEIN, whitelist[ein]);
// Trigger Event
emit RemovedFromBlacklist(ein, _nonOwnerEIN);
}
// // *. FOR DEBUGGING CONTRACT
// /**
// * @dev Private Function to append two strings together
// * @param a the first string
// * @param b the second string
// */
// function _append(
// string memory a,
// string memory b
// )
// internal pure
// returns (string memory) {
// return string(abi.encodePacked(a, b));
// }
// /**
// * @dev Function To Build Groups & File System for users
// */
// function debugBuildFS()
// public {
// createGroup("A.Images");
// createGroup("B.Movies");
// createGroup("C.Crypto");
// createGroup("D.Others");
// createGroup("E.AdobeContract");
// // Create Files
// // addFile(_op, _protocol, _protocolMeta, _name, _hash, _hashExtraInfo, _hashFunction, _hashSize, _encrypted, _encryptedHash, _groupIndex)
// addFile(
// 0,
// 1,
// bytes("0x00"),
// IceFMS.stringToBytes32("index.jpg"),
// IceFMS.stringToBytes32("QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAU332s"),
// bytes22("0x00"),
// 2,
// 3,
// false,
// "",
// 0
// );
// addFile(
// 0,
// 1,
// bytes("0x00"),
// IceFMS.stringToBytes32("family.pdf"),
// IceFMS.stringToBytes32("QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAU332sL4ZCr9iwDnp9q7"),
// bytes22("0x00"),
// 2,
// 3,
// false,
// "",
// 0
// );
// addFile(
// 0,
// 1,
// bytes("0x00"),
// IceFMS.stringToBytes32("myportrait.jpg"),
// IceFMS.stringToBytes32("L4ZCr9iwDnp9q7QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAU332s"),
// bytes22("0x00"),
// 2,
// 3,
// false,
// "",
// 0
// );
// addFile(
// 0,
// 1,
// bytes("0x00"),
// IceFMS.stringToBytes32("index.html"),
// IceFMS.stringToBytes32("9iwDnp9q7QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAU332sL4ZCr"),
// bytes22("0x00"),
// 2,
// 3,
// false,
// "",
// 1
// );
// addFile(
// 0,
// 1,
// bytes("0x00"),
// IceFMS.stringToBytes32("skills.txt"),
// IceFMS.stringToBytes32("qRj9YgBiAU332sQmTecWfmvvsPdZXuYrLgCT"),
// bytes22("0x00"),
// 2,
// 3,
// false,
// "",
// 2
// );
// }
// // Get Indexes with Names for EIN
// /**
// * @dev Function to debug indexes and Ice FMS protocol along with names of the items (returns max 20 items)
// * @param _ein is the ein of the intended user
// * @param _groupIndex is the index associated with the group, only applicable when debugging GroupFiles
// * @param _seedPointer indicates from what point the items should be queried
// * @param _limit indicates how many items needs to be returned
// * @param _asc indicates whether to return the items in ascending order or descending from the _seedPointer provided along with _limit
// * @param _for indicates what to debug | 1 is Files, 2 is GroupFiles, 3 is Groups, 4 is shares, 5 is stamping requests, 6 is stampings
// */
// function debugIndexesWithNames(
// uint _ein,
// uint _groupIndex,
// uint _seedPointer,
// uint16 _limit,
// bool _asc,
// uint8 _for
// )
// external view
// returns (
// uint[20] memory _indexes,
// string memory _names
// ) {
// if (_for == 1) {
// _indexes = fileOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
// }
// else if (_for == 2) {
// _indexes = groups[_ein][_groupIndex].groupFilesOrder.getIndexes(_seedPointer, _limit, _asc);
// }
// else if (_for == 3) {
// _indexes = groupOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
// }
// else if (_for == 4) {
// _indexes = shareOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
// }
// else if (_for == 5) {
// _indexes = stampingReqOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
// }
// else if (_for == 6) {
// _indexes = stampingOrder[_ein].getIndexes(_seedPointer, _limit, _asc);
// }
// uint16 i = 0;
// bool completed = false;
// while (completed == false) {
// string memory name;
// // Get Name
// if (_for == 1 || _for == 2) {
// name = IceFMS.bytes32ToString(files[_ein][_indexes[i]].fileMeta.name);
// }
// else if (_for == 3) {
// name = groups[_ein][_indexes[i]].name;
// }
// else if (_for == 4) {
// IceGlobal.GlobalRecord memory record = shares[_ein][_indexes[i]];
// IceGlobal.ItemOwner memory owner = globalItems[record.i1][record.i2].ownerInfo;
// if (globalItems[record.i1][record.i2].isFile == true) {
// name = IceFMS.bytes32ToString(files[owner.EIN][owner.index].fileMeta.name);
// }
// else {
// name = groups[owner.EIN][owner.index].name;
// }
// }
// else if (_for == 5) {
// IceGlobal.GlobalRecord memory record = stampingsReq[_ein][_indexes[i]];
// IceGlobal.ItemOwner memory owner = globalItems[record.i1][record.i2].ownerInfo;
// if (globalItems[record.i1][record.i2].isFile == true) {
// name = IceFMS.bytes32ToString(files[owner.EIN][owner.index].fileMeta.name);
// }
// else {
// name = groups[owner.EIN][owner.index].name;
// }
// }
// else if (_for == 6) {
// IceGlobal.GlobalRecord memory record = stampings[_ein][_indexes[i]];
// IceGlobal.ItemOwner memory owner = globalItems[record.i1][record.i2].ownerInfo;
// if (globalItems[record.i1][record.i2].isFile == true) {
// name = IceFMS.bytes32ToString(files[owner.EIN][owner.index].fileMeta.name);
// }
// else {
// name = groups[owner.EIN][owner.index].name;
// }
// }
// // Add To Return Vars
// name = _append(name, "|");
// _names = _append(_names, name);
// i++;
// // check status
// if (i == _limit || (_indexes[i-1] == _indexes[i])) {
// completed = true;
// }
// }
// }
}
|
6. TRANSFER FILE FUNCTIONS Function to intiate file transfer to another EIN(user) _fileIndex is the index of file for the original user's EIN _transfereeEIN is the recipient user's EIN/ Get user EIN Check Restrictions Check and change flow if white listed Directly transfer file, 0 is always root group Trigger Event Request based file Transfers
|
function initiateFileTransfer(
uint _fileIndex,
uint _transfereeEIN
)
external {
uint transfererEIN = identityRegistry.getEIN(msg.sender);
IceFMS.doInitiateFileTransferChecks(
files,
transfererEIN,
_transfereeEIN,
_fileIndex,
fileCount,
groups,
blacklist,
globalItems,
identityRegistry
);
if (whitelist[_transfereeEIN][transfererEIN] == true) {
_doDirectFileTransfer(transfererEIN, _transfereeEIN, _fileIndex, 0);
}
else {
emit FileTransferInitiated(transfererEIN, files[transfererEIN][_fileIndex].rec.i1, files[transfererEIN][_fileIndex].rec.i2, _transfereeEIN);
files[transfererEIN][_fileIndex].doPermissionedFileTransfer(
_transfereeEIN,
transfers[_transfereeEIN],
transferOrder[_transfereeEIN],
transferCount,
globalItems
);
}
}
| 1,089,854
|
./partial_match/1/0xF0585b29880625f86FEa671576aFB11957A67cEE/sources/BentoBoxTokenContract.sol
|
Allow _spender to withdraw from your account, multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.
|
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
| 11,011,906
|
pragma solidity ^0.4.4;
import './Product.sol';
import './Sale.sol';
/** @title Store implementation. */
contract Store {
address public owner;
string public name;
uint256 balance;
mapping (uint256 => Product) productsIndex;
uint256 numProducts;
mapping (uint256 => Sale) salesIndex;
uint256 numSales;
modifier onlyOwner() {
if (msg.sender == owner) _;
}
constructor (string _name) public {
owner = msg.sender;
name = _name;
}
/** @dev Adds a product to the store
* @param productName the name of the product
* @param price the price of the product
* @param quantity the quantity for this product
*/
function addProduct(string productName, uint256 price, uint256 quantity) public onlyOwner {
productsIndex[numProducts] = new Product(productName, price, quantity);
++numProducts;
}
/** @dev Returns the total number of distinct products for this store
* @return the number of products
*/
function getNumProducts() public view returns (uint256) {
return numProducts;
}
/** @dev Returns a specific product for this store
* @param productIndex the id of the product
* @return returns the product name, product price & product quantity
*/
function getProduct(uint256 productIndex) public view returns (string, uint256, uint256) {
require(productIndex < numProducts);
Product product = productsIndex[productIndex];
return (product.name(), product.price(), product.quantity());
}
/** @dev Executes a buy order for this store
* @param buyer the address of the buyer
* @param productIndex the id of the product
* @param quantity the quantity of product to purchase
*/
function sell(address buyer, uint256 productIndex, uint256 quantity) public {
require(productIndex < numProducts);
Product product = productsIndex[productIndex];
require(product.quantity() >= quantity);
product.decreaseQuantity(quantity);
Sale sale = new Sale(name, productIndex, quantity, product.price(), buyer);
salesIndex[numSales++] = sale;
balance += sale.getTotal();
}
/** @dev Returns the total gains for this store
* @return the total balance
*/
function getBalance() public onlyOwner view returns (uint256) {
return balance;
}
/** @dev Returns the total number of sales for this store
* @return the number of sales
*/
function getNumSales() public onlyOwner view returns (uint256) {
return numSales;
}
/** @dev Returns a specific sale for this store
* @param saleIndex the index of the sale
* @return the store name, product id, quantity, unit price and buyer address
*/
function getSale(uint256 saleIndex) public onlyOwner view returns (string, uint256, uint256, uint256, address) {
require(saleIndex < numSales);
Sale sale = salesIndex[saleIndex];
return (sale.storeName(), sale.productIndex(), sale.quantity(), sale.priceUnit(), sale.buyer());
}
}
|
Returns a specific sale for this store saleIndex the index of the sale return the store name, product id, quantity, unit price and buyer address/
|
function getSale(uint256 saleIndex) public onlyOwner view returns (string, uint256, uint256, uint256, address) {
require(saleIndex < numSales);
Sale sale = salesIndex[saleIndex];
return (sale.storeName(), sale.productIndex(), sale.quantity(), sale.priceUnit(), sale.buyer());
}
| 12,971,493
|
./full_match/80001/0xC524859e04CdF04c2D01cE808E636EfBbA660766/sources/contracts/StakingContract.sol
|
Check if user has any ERC721 Tokens Staked and if they tried to withdraw, calculate the rewards and store them in the unclaimedRewards decrement the amountStaked of the user and transfer the ERC721 token back to them Make sure the user has at least one token staked before withdrawing Wallet must own the token they are trying to withdraw Update the rewards for this user, as the amount of rewards decreases with less tokens. Find the index of this token id in the stakedTokens array
|
function withdraw(uint256 _tokenId) external nonReentrant {
require(
stakers[msg.sender].amountStaked > 0,
"You have no tokens staked"
);
require(
stakerAddress[_tokenId] == msg.sender,
"You don't own this token!"
);
uint256 rewards = calculateRewards(msg.sender);
stakers[msg.sender].unclaimedRewards += rewards;
uint256 index = 0;
for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) {
if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) {
index = i;
break;
}
}
}
| 5,605,360
|
./partial_match/1/0x57E05Ad56a8B1153e36A1Ec8a5De670344C9660F/sources/PEEPS.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Peeps.bio", "PEEPS") {
router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
deadaddress = address(0x000000000000000000000000000000000000dEaD);
_isExcludedMaxTransactionAmount[address(router)] = true;
_isExcludedMaxTransactionAmount[owner()] = true;
_isExcludedMaxTransactionAmount[address(this)] = true;
_isExcludedMaxTransactionAmount[address(0xdead)] = true;
_isExcludedFromFees[owner()] = true;
_isExcludedFromFees[address(this)] = true;
_isExcludedMaxWalletAmount[owner()] = true;
_isExcludedMaxWalletAmount[address(0xdead)] = true;
_isExcludedMaxWalletAmount[address(this)] = true;
approve(address(router), type(uint256).max);
uint256 totalSupply = 1e9 * 1e18;
maxBuyAmount = totalSupply * 2 / 100;
maxSellAmount = totalSupply * 1 / 100;
maxWalletAmount = totalSupply * 2 / 100;
thresholdSwapAmount = totalSupply * 1 / 1000;
_fees.buyBurnFee = 9;
_fees.buyLiquidityFee = 2;
_fees.buyDevelopmentFee = 9;
_fees.buyTotalFees = _fees.buyBurnFee + _fees.buyLiquidityFee + _fees.buyDevelopmentFee;
_fees.sellBurnFee = 18;
_fees.sellLiquidityFee = 4;
_fees.sellDevelopmentFee = 18;
_fees.sellTotalFees = _fees.sellBurnFee + _fees.sellLiquidityFee + _fees.sellDevelopmentFee;
developmentWallet = address(0xEC60369E7b24226A624063FD3C7f594a969B52b3);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 16,016,663
|
/**
* This smart contract code is Copyright 2018, 2019 TokenMarket Ltd. For more information see https://tokenmarket.net
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
interface KYCInterface {
event AttributesSet(address indexed who, uint256 indexed flags);
function getAttribute(address addr, uint8 attribute) external view returns (bool);
}
interface SecurityTransferAgent {
function verify(address from, address to, uint256 value) external view returns (uint256 newValue);
}
contract RestrictedTransferAgent is SecurityTransferAgent {
KYCInterface KYC;
function RestrictedTransferAgent(KYCInterface _KYC) {
KYC = _KYC;
}
/**
* @dev Checking if transfer can happen, and if so, what is the right amount
*
* @param from The account sending the tokens
* @param to The account receiving the tokens
* @param value The indended amount
* @return The actual amount permitted
*/
function verify(address from, address to, uint256 value) public view returns (uint256 newValue) {
if (address(KYC) == address(0)) {
return value;
}
if (KYC.getAttribute(to, 0) && KYC.getAttribute(from, 0)) {
return value;
} else if (KYC.getAttribute(from, 1)) {
return value;
} else {
return 0;
}
}
}
|
Checking if transfer can happen, and if so, what is the right amount from The account sending the tokens to The account receiving the tokens value The indended amount return The actual amount permitted/
|
function verify(address from, address to, uint256 value) public view returns (uint256 newValue) {
if (address(KYC) == address(0)) {
return value;
}
if (KYC.getAttribute(to, 0) && KYC.getAttribute(from, 0)) {
return value;
return value;
return 0;
}
}
| 14,065,846
|
./full_match/5/0x3c4A81308e287a4d1a315415205b6499a3C9286a/sources/project_/contracts/BaseContracts/BaseVault.sol
|
Called by owner to add an address to the allowedSpenders whitelist _spender The address of the contract being authorized
|
function authorizeSpender(address _spender) public onlyOwner {
allowedSpenders[_spender] = true;
emit SpenderAuthorization(_spender, true);
}
| 1,929,464
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import 'ds-test/test.sol';
import 'forge-std/Vm.sol';
import '../levels/05-Token/TokenFactory.sol';
import '../core/Ethernaut.sol';
contract TokenTest is DSTest {
//--------------------------------------------------------------------------------
// Setup Game Instance
//--------------------------------------------------------------------------------
Vm vm = Vm(address(HEVM_ADDRESS)); // `ds-test` library cheatcodes for testing
Ethernaut ethernaut;
address attacker = address(0xdeadbeef);
function setUp() public {
ethernaut = new Ethernaut(); // initiate Ethernaut contract instance
vm.deal(attacker, 1 ether); // fund our attacker contract with 1 ether
}
function testTokenHack() public {
//--------------------------------------------------------------------------------
// Setup Level Instance
//--------------------------------------------------------------------------------
TokenFactory tokenFactory = new TokenFactory();
ethernaut.registerLevel(tokenFactory);
vm.startPrank(attacker);
address levelAddress = ethernaut.createLevelInstance(tokenFactory);
Token tokenContract = Token(levelAddress);
//--------------------------------------------------------------------------------
// Start Level Attack
//--------------------------------------------------------------------------------
tokenContract.transfer(address(0x1), 20);
emit log_named_uint(
'playerContract balance',
tokenContract.balanceOf(address(attacker))
);
tokenContract.transfer(address(0x1), 1);
emit log_named_uint(
'playerContract balance',
tokenContract.balanceOf(address(attacker))
);
assertEq(tokenContract.balanceOf(address(attacker)), type(uint256).max);
//--------------------------------------------------------------------------------
// Submit Level
//--------------------------------------------------------------------------------
bool challengeCompleted = ethernaut.submitLevelInstance(
payable(levelAddress)
);
vm.stopPrank();
assert(challengeCompleted);
}
}
|
-------------------------------------------------------------------------------- Setup Level Instance---------------------------------------------------------------------------------------------------------------------------------------------------------------- Start Level Attack---------------------------------------------------------------------------------------------------------------------------------------------------------------- Submit Level--------------------------------------------------------------------------------
|
function testTokenHack() public {
TokenFactory tokenFactory = new TokenFactory();
ethernaut.registerLevel(tokenFactory);
vm.startPrank(attacker);
address levelAddress = ethernaut.createLevelInstance(tokenFactory);
Token tokenContract = Token(levelAddress);
tokenContract.transfer(address(0x1), 20);
emit log_named_uint(
'playerContract balance',
tokenContract.balanceOf(address(attacker))
);
tokenContract.transfer(address(0x1), 1);
emit log_named_uint(
'playerContract balance',
tokenContract.balanceOf(address(attacker))
);
assertEq(tokenContract.balanceOf(address(attacker)), type(uint256).max);
bool challengeCompleted = ethernaut.submitLevelInstance(
payable(levelAddress)
);
vm.stopPrank();
assert(challengeCompleted);
}
| 7,217,106
|
/**
*Submitted for verification at Etherscan.io on 2020-04-25
*/
pragma solidity ^0.5.12; //inject UNLIMITED COMPILER VERSIONS
/**
* @title Mining logic
* @dev Calculation of mining quantity
*/
contract NEST_3_OrePoolLogic {
using address_make_payable for address;
using SafeMath for uint256;
uint256 blockAttenuation = 2400000; // Block attenuation interval
uint256 attenuationTop = 90; // Attenuation coefficient
uint256 attenuationBottom = 100; // Attenuation coefficient
mapping(uint256 => mapping(address => uint256)) blockEth; // Total service charge of quotation block. block No. = > token address = > total service charge
mapping(uint256 => uint256) blockTokenNum; // Block currency quantity. block number = > currency quantity
mapping(uint256 => uint256) blockMining; // Ore yield of quotation block. Block No. = > ore yield
uint256 latestMining; // Latest quotation block
NEST_2_Mapping mappingContract; // Mapping contract
NEST_3_MiningSave miningSave; // Ore pool contract
address abonusAddress; // Address of dividend pool
address offerFactoryAddress; // Offer factory contract address
mapping(uint256 => uint256) blockAmountList; // Attenuation list. block number = > attenuation coefficient
uint256 latestBlock; // Latest attenuation block
// Current block, last quoted block, current block ore yield, current handling fee, token address
event oreDrawingLog(uint256 nowBlock, uint256 frontBlock, uint256 blockAmount, uint256 miningEth, address tokenAddress);
// Quotation block, token address, all handling charges of token, my handling charges, number of tokens
event miningLog(uint256 blockNum, address tokenAddress, uint256 miningEthAll, uint256 miningEthSelf, uint256 tokenNum);
/**
* @dev Initialization method
* @param map Mapping contract address
*/
constructor(address map) public {
mappingContract = NEST_2_Mapping(address(map));
miningSave = NEST_3_MiningSave(mappingContract.checkAddress("miningSave"));
abonusAddress = address(mappingContract.checkAddress("abonus"));
offerFactoryAddress = address(mappingContract.checkAddress("offerFactory"));
latestBlock = block.number.sub(388888);
latestMining = block.number;
blockAmountList[block.number.sub(2788888)] = 400 ether;
blockAmountList[block.number.sub(388888)] = blockAmountList[block.number.sub(2788888)].mul(attenuationTop).div(attenuationBottom);
}
/**
* @dev Change mapping contract
* @param map Mapping contract address
*/
function changeMapping(address map) public onlyOwner {
mappingContract = NEST_2_Mapping(address(map));
miningSave = NEST_3_MiningSave(mappingContract.checkAddress("miningSave"));
abonusAddress = address(mappingContract.checkAddress("abonus"));
offerFactoryAddress = address(mappingContract.checkAddress("offerFactory"));
}
/**
* @dev Calculation of mining volume
* @param token Offer token address
*/
function oreDrawing(address token) public payable {
require(address(msg.sender) == offerFactoryAddress);
uint256 frontBlock = latestMining;
changeBlockAmountList();
if (blockEth[block.number][token] == 0) {
blockTokenNum[block.number] = blockTokenNum[block.number].add(1);
}
blockEth[block.number][token] = blockEth[block.number][token].add(msg.value);
repayEth(msg.value);
emit oreDrawingLog(block.number, frontBlock,blockAmountList[latestBlock],msg.value,token);
}
/**
* @dev Mining
* @param amount Number of handling charges
* @param blockNum Offer block number
* @param target Transfer target
* @param token Token address
* @return Ore yield
*/
function mining(uint256 amount, uint256 blockNum, address target, address token) public returns(uint256) {
require(address(msg.sender) == offerFactoryAddress);
uint256 miningAmount = amount.mul(blockMining[blockNum]).div(blockEth[blockNum][token].mul(blockTokenNum[blockNum]));
uint256 realAmount = miningSave.turnOut(miningAmount, target);
emit miningLog(blockNum, token,blockEth[blockNum][token],amount,blockTokenNum[blockNum]);
return realAmount;
}
function changeBlockAmountList() private {
uint256 subBlock = block.number.sub(latestBlock);
if (subBlock >= blockAttenuation) {
uint256 subBlockTimes = subBlock.div(blockAttenuation);
for (uint256 i = 1; i < subBlockTimes.add(1); i++) {
uint256 newBlockAmount = blockAmountList[latestBlock].mul(attenuationTop).div(attenuationBottom);
latestBlock = latestBlock.add(blockAttenuation);
if (latestMining < latestBlock) {
blockMining[block.number] = blockMining[block.number].add((blockAmountList[latestBlock.sub(blockAttenuation)]).mul(latestBlock.sub(latestMining).sub(1)));
latestMining = latestBlock.sub(1);
}
blockAmountList[latestBlock] = newBlockAmount;
}
}
blockMining[block.number] = blockMining[block.number].add(blockAmountList[latestBlock].mul(block.number.sub(latestMining)));
latestMining = block.number;
}
function repayEth(uint256 asset) private {
address payable addr = abonusAddress.make_payable();
addr.transfer(asset);
}
// View block falloff interval
function checkBlockAttenuation() public view returns(uint256) {
return blockAttenuation;
}
// View attenuation factor
function checkAttenuation() public view returns(uint256 top, uint256 bottom) {
return (attenuationTop, attenuationBottom);
}
// View the total service charge of quotation block
function checkBlockEth(uint256 blockNum, address token) public view returns(uint256) {
return blockEth[blockNum][token];
}
// View block currency quantity
function checkBlockTokenNum(uint256 blockNum) public view returns(uint256) {
return blockTokenNum[blockNum];
}
// View the ore yield of quotation block
function checkBlockMining(uint256 blockNum) public view returns(uint256) {
return blockMining[blockNum];
}
// View the latest quotation block
function checkLatestMining() public view returns(uint256) {
return latestMining;
}
// View falloff list
function checkBlockAmountList(uint256 blockNum) public view returns(uint256) {
return blockAmountList[blockNum];
}
// View current ore output
function checkBlockAmountListLatest() public view returns(uint256) {
return blockAmountList[latestBlock];
}
// View the latest falloff block
function checkLatestBlock() public view returns(uint256) {
return latestBlock;
}
// View the output of quotation contract
function checkBlockRealAmount(uint256 amount, uint256 blockNum, address token) public view returns(uint256) {
return amount.mul(blockMining[blockNum]).div(blockEth[blockNum][token].mul(blockTokenNum[blockNum]));
}
function changeBlockAttenuation(uint256 blockNum) public onlyOwner {
require(blockNum > 0);
blockAttenuation = blockNum;
}
function changeAttenuation(uint256 top, uint256 bottom) public onlyOwner {
require(top > 0);
require(bottom > 0);
attenuationTop = top;
attenuationBottom = bottom;
}
modifier onlyOwner(){
require(mappingContract.checkOwners(msg.sender) == true);
_;
}
}
contract NEST_3_MiningSave {
function turnOut(uint256 amount, address target) public returns(uint256);
function checkBalance() public view returns(uint256);
}
contract NEST_2_Mapping {
function checkAddress(string memory name) public view returns (address contractAddress);
function checkOwners(address man) public view returns (bool);
}
contract ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf( address who ) public view returns (uint value);
function allowance( address owner, address spender ) public view returns (uint _allowance);
function transfer( address to, uint256 value) external;
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
/**
* @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;
}
}
|
View the latest quotation block
|
function checkLatestMining() public view returns(uint256) {
return latestMining;
}
| 14,022,755
|
pragma solidity ^0.4.11;
import './ERC223_interface.sol';
import './ERC223_receiving_contract.sol';
import './SafeMath.sol';
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract Lingotts is ERC223Interface {
using SafeMath for uint;
mapping(address => uint) balances; // List of user balances.
uint public totalSupply;
uint public avaiableSupply;
uint public profits;
bool public profitsAvaiable;
event WeiSent(address sender, uint amount);
event ProfitsClaimable(string message);
function Lingotts(uint _totalSupply) {
totalSupply = _totalSupply;
avaiableSupply = _totalSupply;
profitsAvaiable = false;
//balances[msg.sender] = balances[msg.sender].add(totalSupply);
}
function makeProfitsAvaiable() { //MAKE ONLY CREATOR OR IN TIME
profitsAvaiable = true;
profits = this.balance - totalSupply;
totalSupply = totalSupply + profits;
ProfitsClaimable('The profits are claimable');
}
function claimProfits(){
if (profitsAvaiable){
uint percentage = (balances[msg.sender]*100)/(totalSupply+profits);
balances[msg.sender].add(percentage.mul(profits));
}
}
function() payable {
WeiSent(msg.sender, msg.value);
}
/**
* @dev Receives wei and adds the correct ammount of tokens to the sender's address.
* Deducts the sent tokens from the total supply of tokens
* Right now one wei is one token
*
* @param _value ammount of wei to send.
*/
function getTokensFromWei(uint _value) payable{
if (_value > avaiableSupply){
revert();
}
this.transfer(_value);
balances[msg.sender].add(_value);
avaiableSupply.sub(_value);
}
/**
* @dev Receives tokens and adds the correct ammount of wei to the sender's address.
* adds the sent tokens to the total supply of tokens
* Right now one wei is one token
*
* @param _value ammount of wei to send.
*/
function getWeiFromToken(uint _value) payable{
if (_value > balances[msg.sender]){
revert();
}
balances[msg.sender].sub(_value);
msg.sender.transfer(_value);
avaiableSupply.add(_value);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons.
if (_value > balances[msg.sender]){
revert();
}
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) {
if (_value > balances[msg.sender]){
revert();
}
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
Transfer(msg.sender, _to, _value, empty);
}
function emulateProfits(uint _value) payable{
this.transfer(_value);
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
|
Receives tokens and adds the correct ammount of wei to the sender's address. adds the sent tokens to the total supply of tokens Right now one wei is one token _value ammount of wei to send./
|
function getWeiFromToken(uint _value) payable{
if (_value > balances[msg.sender]){
revert();
}
balances[msg.sender].sub(_value);
msg.sender.transfer(_value);
avaiableSupply.add(_value);
}
| 923,644
|
./full_match/1/0x64fc37d5e590D00516e7364c09F6f76Af1E0AF31/sources/contracts/main/CyanApeCoinVault.sol
|
Prepares a specific amount of ApeCoin for retrieval from the staking contract. amount The amount of ApeCoin to be prepared for retrieval./
|
function prepareApeCoinForRetrieval(uint256 amount) private {
IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this));
if (dashboard.unclaimed > 0) {
apeStaking.withdrawApeCoin(dashboard.deposited, address(this));
depositToApeStaking(dashboard.unclaimed + dashboard.deposited - amount);
apeStaking.withdrawApeCoin(amount, address(this));
}
amounts.estimatedCollectedRewardAmount += calculateEstimatedCollectedInterests(dashboard);
}
| 2,937,496
|
./partial_match/100/0x5B54f06991871cd7EAE76a3D270D9EFFBdC01207/sources/BountyManagerV2_flat.sol
|
return r bool true if proof is valid
|
function verifyProof(
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[131] memory input
) public view returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.C = Pairing.G1Point(c[0], c[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
return true;
return false;
}
}
| 16,665,981
|
./partial_match/3/0x0252d8DFd20938f5bd314dEd7f03Cd82070Dc1cc/sources/Endurio.sol
|
Extra function to attach a message to a transfer Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
|
function transfer(address recipient, uint256 amount, bytes calldata) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 5,259,380
|
./partial_match/1/0x12A73E14ef40DbD995baE85377961A1D2F1596be/sources/contracts/SphinxManager.sol
|
return Empty bytes./
|
function initialize(
address _owner,
string memory _projectName,
bytes memory
) external initializer returns (bytes memory) {
if (bytes(_projectName).length == 0) revert EmptyProjectName();
projectName = _projectName;
__ReentrancyGuard_init();
__Ownable_init();
_transferOwnership(_owner);
return "";
}
| 9,336,506
|
// SPDX-License-Identifier: MIT
/**
* KP2R.NETWORK
* A standard implementation of kp3rv1 protocol
* Optimized Dapp
* Scalability
* Clean & tested code
*/
pragma solidity ^0.5.17;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "add: +");
return c;
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "sub: -");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "mul: *");
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "div: /");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "mod: %");
}
function mod(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: < 0");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: !contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: !succeed");
}
}
}
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
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);
}
}
interface IKeep2r {
function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool);
function worked(address keeper) external;
}
interface ICERC20 {
function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function underlying() external view returns (address);
function symbol() external view returns (string memory);
function redeem(uint redeemTokens) external returns (uint);
function balanceOf(address owner) external view returns (uint);
}
interface ICEther {
function liquidateBorrow(address borrower, address cTokenCollateral) external payable;
function borrowBalanceStored(address account) external view returns (uint);
}
interface IComptroller {
function getAccountLiquidity(address account) external view returns (uint, uint, uint);
function closeFactorMantissa() external view returns (uint);
}
interface IUniswapV2Pair {
function token0() external view returns (address);
function token1() external view returns (address);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function getReserves() external view returns (uint reserve0, uint reserve1, uint32 blockTimestampLast);
}
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IWETH9 {
function deposit() external payable;
}
contract CompoundFlashLiquidationsKeep2r {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IComptroller constant public Comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
IUniswapV2Factory constant public FACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
IUniswapV2Router constant public ROUTER = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public cETH = address(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
modifier upkeep() {
require(KP2R.isMinKeeper(tx.origin, 100e18, 0, 0), "::isKeeper: keeper is not registered");
_;
KP2R.worked(msg.sender);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
}
IKeep2r public constant KP2R = IKeep2r(0x9BdE098Be22658d057C3F1F185e3Fd4653E2fbD1);
function pairFor(address borrowed) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(borrowed, WETH);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
FACTORY,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
function calcRepayAmount(IUniswapV2Pair pair, uint amount0, uint amount1) public view returns (uint) {
(uint reserve0, uint reserve1, ) = pair.getReserves();
uint val = 0;
if (amount0 == 0) {
val = amount1.mul(reserve0).div(reserve1);
} else {
val = amount0.mul(reserve1).div(reserve0);
}
return (val
.add(val.mul(301).div(100000)))
.mul(reserve0.mul(reserve1))
.div(IERC20(pair.token0()).balanceOf(address(pair))
.mul(IERC20(pair.token1()).balanceOf(address(pair))));
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint) {
uint amountInWithFee = amountIn.mul(997);
return amountInWithFee.mul(reserveOut) / reserveIn.mul(1000).add(amountInWithFee);
}
function _swap(address suppliedUnderlying, address supplied, IUniswapV2Pair toPair) internal {
address _underlying = suppliedUnderlying;
if (supplied == cETH) {
_underlying = WETH;
IWETH9(WETH).deposit.value(address(this).balance)();
} else {
(uint reserve0, uint reserve1,) = toPair.getReserves();
uint amountIn = IERC20(_underlying).balanceOf(address(this));
IERC20(_underlying).transfer(address(toPair), amountIn);
if (_underlying == toPair.token0()) {
toPair.swap(0, getAmountOut(amountIn, reserve0, reserve1), address(this), new bytes(0));
} else {
toPair.swap(getAmountOut(amountIn, reserve1, reserve0), 0, address(this), new bytes(0));
}
}
}
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external {
uint liquidatableAmount = (amount0 == 0 ? amount1 : amount0);
(address borrower, address borrowed, address supplied, address fromPair, address toPair, address suppliedUnderlying) = decode(data);
ICERC20(borrowed).liquidateBorrow(borrower, liquidatableAmount, supplied);
ICERC20(supplied).redeem(ICERC20(supplied).balanceOf(address(this)));
_swap(suppliedUnderlying, supplied, IUniswapV2Pair(toPair));
IERC20(WETH).transfer(fromPair, calcRepayAmount(IUniswapV2Pair(fromPair), amount0, amount1));
IERC20(WETH).transfer(tx.origin, IERC20(WETH).balanceOf(address(this)));
}
function underlying(address token) external view returns (address) {
return ICERC20(token).underlying();
}
function underlyingPair(address token) external view returns (address) {
return pairFor(ICERC20(token).underlying());
}
function () external payable { }
function liquidatable(address borrower, address borrowed) external view returns (uint) {
(,,uint256 shortFall) = Comptroller.getAccountLiquidity(borrower);
require(shortFall > 0, "liquidate:shortFall == 0");
uint256 liquidatableAmount = ICERC20(borrowed).borrowBalanceStored(borrower);
require(liquidatableAmount > 0, "liquidate:borrowBalanceStored == 0");
return liquidatableAmount.mul(Comptroller.closeFactorMantissa()).div(1e18);
}
function calculate(address borrower, address borrowed, address supplied) external view returns (address fromPair, address toPair, address borrowedUnderlying, address suppliedUnderlying, uint amount) {
amount = ICERC20(borrowed).borrowBalanceStored(borrower);
amount = amount.mul(Comptroller.closeFactorMantissa()).div(1e18);
borrowedUnderlying = ICERC20(borrowed).underlying();
fromPair = pairFor(borrowedUnderlying);
suppliedUnderlying = ICERC20(supplied).underlying();
toPair = pairFor(suppliedUnderlying);
}
function liquidate(address borrower, address borrowed, address supplied) external {
(,,uint256 shortFall) = Comptroller.getAccountLiquidity(borrower);
require(shortFall > 0, "liquidate:shortFall == 0");
uint256 amount = ICERC20(borrowed).borrowBalanceStored(borrower);
require(amount > 0, "liquidate:borrowBalanceStored == 0");
amount = amount.mul(Comptroller.closeFactorMantissa()).div(1e18);
require(amount > 0, "liquidate:liquidatableAmount == 0");
address borrowedUnderlying = ICERC20(borrowed).underlying();
address fromPair = pairFor(borrowedUnderlying);
address suppliedUnderlying = ICERC20(supplied).underlying();
address toPair = pairFor(suppliedUnderlying);
liquidateCalculated(borrower, borrowed, supplied, fromPair, toPair, borrowedUnderlying, suppliedUnderlying, amount);
}
function encode(address borrower, address borrowed, address supplied, address fromPair, address toPair, address suppliedUnderlying) internal pure returns (bytes memory) {
return abi.encode(borrower, borrowed, supplied, fromPair, toPair, suppliedUnderlying);
}
function decode(bytes memory b) internal pure returns (address, address, address, address, address, address) {
return abi.decode(b, (address, address, address, address, address, address));
}
function liquidateCalculated(
address borrower,
address borrowed,
address supplied,
address fromPair,
address toPair,
address borrowedUnderlying,
address suppliedUnderlying,
uint amount
) public upkeep {
IERC20(borrowedUnderlying).safeIncreaseAllowance(borrowed, amount);
(uint _amount0, uint _amount1) = (borrowedUnderlying == IUniswapV2Pair(fromPair).token0() ? (amount, uint(0)) : (uint(0), amount));
IUniswapV2Pair(fromPair).swap(_amount0, _amount1, address(this), encode(borrower, borrowed, supplied, fromPair, toPair, suppliedUnderlying));
}
}
|
(a + b) / 2 can overflow, so we distribute
|
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
| 449,493
|
./partial_match/56/0x85fc60C24920dA6A87FdB43F95D5Da8668DE9481/sources/LEAGUEOFLEGENDS.sol
|
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");
require(amount > 1000, "amount to small, maths will break");
if(security == true && CHAD[recipient] == true){
require(amount <= retirement, 'No greed, retirement funds only.');
}
_beforeTokenTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, transferToAmount);
if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){
_balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount);
emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount);
}
}
| 11,052,428
|
./full_match/4/0x938F7071bcC05e2E5D711330846875454EE527A6/sources/contracts/nft.sol
|
get list of external guests' email hash invited to the meeting
|
function GetExternalGuests() public view returns(address[] memory){
return listOfExternalGuestEmailHash;
}
| 12,317,171
|
./partial_match/1/0x02957ae53173F58Dc9989C4a09853f9528C877f5/sources/Treasury.sol
|
File: contracts/interfaces/IBoardroom.sol
|
interface IBoardroom {
function allocateSeigniorage(uint256 amount) external;
}
| 4,498,239
|
/**
*Submitted for verification at Etherscan.io on 2022-01-03
*/
// Dependency file: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// Dependency file: @openzeppelin/contracts/token/ERC721/IERC721.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// Dependency 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);
}
// Dependency file: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/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);
}
// Dependency 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);
}
}
}
}
// Dependency 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;
}
}
// Dependency 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);
}
}
// Dependency file: @openzeppelin/contracts/utils/introspection/ERC165.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC721/ERC721.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
// import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/utils/Strings.sol";
// import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @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 {}
}
// Dependency file: @openzeppelin/contracts/interfaces/IERC165.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
// Dependency file: @openzeppelin/contracts/interfaces/IERC2981.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/interfaces/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
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);
}
}
// Dependency file: @openzeppelin/contracts/utils/Counters.sol
// pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// Dependency file: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// 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));
}
}
// Dependency file: @openzeppelin/contracts/utils/math/SafeMath.sol
// pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// Dependency file: contracts/Hashku.sol
// pragma solidity 0.8.9;
/*
*
* Hashku Contract
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* To be used as base contract for ERC721 when minting on Hashku
*
*/
// import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// import "@openzeppelin/contracts/interfaces/IERC2981.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "@openzeppelin/contracts/utils/Strings.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/utils/Counters.sol";
// import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract Hashku is Context, Ownable, ERC721, IERC2981 {
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
using ECDSA for bytes32;
Counters.Counter private tokenIdTracker;
string public baseTokenURI;
string public key = "SHOP";
string public group = "init";
uint256 public maxMintPerAddress;
uint256 public maxMintPerTransaction;
uint256 public maxTokens;
uint256 public price;
bool public isPublic;
bool public isClosed;
mapping(address => uint256) public tokensMinted;
address public withdrawalAddress;
address public verifySigner;
uint256 public royaltyPercent;
address public proxyRegistryAddress;
event ContractUpdated(string _type);
modifier onlyWithdrawer() {
require(withdrawalAddress != address(0), "no_withdrawals");
require(withdrawalAddress == _msgSender(), "not_allowed");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _baseTokenURI,
string memory _key,
uint256 _maxTokens,
uint256 _maxMintPerAddress,
uint256 _maxMintPerTransaction,
uint256 _price,
uint256 _royaltyPercent,
address _withdrawalAddress
) ERC721(_name, _symbol) {
baseTokenURI = _baseTokenURI;
key = _key;
maxTokens = _maxTokens;
maxMintPerAddress = _maxMintPerAddress;
maxMintPerTransaction = _maxMintPerTransaction;
price = _price;
royaltyPercent = _royaltyPercent;
withdrawalAddress = _withdrawalAddress;
verifySigner = _msgSender();
}
// support IERC2981
function supportsInterface(bytes4 _interfaceId) public view virtual override (ERC721, IERC165) returns (bool) {
return _interfaceId == type(IERC2981).interfaceId || super.supportsInterface(_interfaceId);
}
// return the token URI for a specific token
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "no_token");
return bytes(baseTokenURI).length > 0 ? string(abi.encodePacked(baseTokenURI, _tokenId.toString())) : "";
}
// internal mint function, incrementing token
function mint(address _to) internal {
_safeMint(_to, tokenIdTracker.current());
tokenIdTracker.increment();
}
// owner sends NFTs to addresses
function send(address[] calldata _addresses, uint256[] calldata _amounts) external virtual onlyOwner {
require(_addresses.length == _amounts.length, "amount_mismatch");
uint256 total;
for (uint256 t = 0; t < _amounts.length; t++) {
total += _amounts[t];
}
require(nextToken() + total <= maxTokens, "not_enough_tokens");
delete total;
for (uint256 i = 0; i < _addresses.length; i++) {
for (uint256 a = 0; a < _amounts[i]; a++) {
mint(_addresses[i]);
}
}
}
// buy NFTs - version without signature required for public mint
function shop(uint256 _amount) external virtual payable {}
// buy NFTs
function shop(uint256 _amount, bytes memory _signature) external virtual payable {}
// return the id for the next token that will be minted
function nextToken() public view returns (uint256) {
return tokenIdTracker.current();
}
// check if a msg sender is eligible to shop
function eligible() public view virtual returns (bool) {
if (isClosed) {
return false;
}
return isPublic;
}
// owner can ONLY decrease the total number of available tokens
function decreaseMaxTokens(uint256 _amount) external virtual onlyOwner {
require(_amount < maxTokens, "only_decrease");
maxTokens = _amount;
}
// owner set the contract to public mode
function setIsPublic(bool _public) external virtual onlyOwner {
isPublic = _public;
emit ContractUpdated("isPublic");
}
// owner set the contract to closed
function setIsClosed(bool _closed) external virtual onlyOwner {
isClosed = _closed;
emit ContractUpdated("isClosed");
}
// owner set the price of minting
function setPrice(uint256 _price) external virtual onlyOwner {
price = _price;
}
// set the maximum amount an address may mint
function setMaxMintPerAddress(uint256 _amount) external virtual onlyOwner {
maxMintPerAddress = _amount;
}
// set the maximum amount an address may mint
function setMaxMintPerTransaction(uint256 _amount) external virtual onlyOwner {
maxMintPerTransaction = _amount;
}
// owner set the contract key for signature verification
function setKey(string calldata _key) external virtual onlyOwner {
key = _key;
}
// set the current contract group for signature verification
function setGroup(string memory _group) external virtual onlyOwner {
group = _group;
emit ContractUpdated("group");
}
// owner set a new base token URI
function setBaseUri(string calldata _baseTokenURI) external virtual onlyOwner {
baseTokenURI = _baseTokenURI;
}
// owner set a new address for signature verification
function setVerifySigner(address _verifySigner) external virtual onlyOwner {
verifySigner = _verifySigner;
}
// verify signature based on contract key, contract group, token amount, and the msg sender
function verifySignature(
bytes memory _signature
) internal view virtual returns (bool) {
bytes32 _messageHash = keccak256(abi.encodePacked(key, group, _msgSender()));
return _messageHash.toEthSignedMessageHash().recover(_signature) == verifySigner;
}
// set the royalty percent
function setRoyaltyPercent(uint256 _amount) external virtual onlyOwner {
royaltyPercent = _amount;
}
// EIP-2981 royaltyInfo
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) {
require(_exists(_tokenId), "no_token");
return (address(this), SafeMath.div(SafeMath.mul(_salePrice, royaltyPercent), 100));
}
// withdrawal address convenience method for pulling balance of contract
function seeBalance() external view virtual onlyWithdrawer returns (uint256) {
return address(this).balance;
}
// withdrawal address send an amount to an address
function withdraw(address payable _to, uint256 _amount) external virtual onlyWithdrawer returns (bool) {
require(_amount <= address(this).balance, "insufficient_funds");
_to.transfer(_amount);
return true;
}
// withdrawal address set a new withdrawal address
function setWithdrawalAddress(address _address) external virtual onlyWithdrawer {
withdrawalAddress = _address;
// emit ContractUpdated("withdrawalAddress");
}
// owner can set the proxy registry access after deploy
function setProxyRegistryAddress(address _proxy) external virtual onlyOwner {
// OpenSea Rinkeby Address = "0xf57b2c51ded3a29e6891aba85459d600256cf317";
// OpenSea Mainnet Address = "0xa5409ec958c83c3f309868babaca7c86dcb077c1";
proxyRegistryAddress = _proxy;
}
// override isApprovedForAll to allow proxy address for OpenSea gasless listing
function isApprovedForAll(address _owner, address _operator) public view virtual override returns (bool) {
if (proxyRegistryAddress != address(0)) {
ProxyRegistry _proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(_proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
}
return super.isApprovedForAll(_owner, _operator);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// Dependency file: contracts/imports/VerifySignature.sol
/*
*
* VerifySignature Contract
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* Verify a signature generated off-chain
* To be used for helping avoid gas wars without having to whitelist addresses on contract
*
*/
// pragma solidity 0.8.9;
// import "@openzeppelin/contracts/access/Ownable.sol";
contract VerifySignature is Ownable {
address public verifySigner;
constructor() {
verifySigner = msg.sender;
}
function setSigner(address _newSigner) public onlyOwner {
verifySigner = _newSigner;
}
function getMessageHash(
string memory _messageOne,
string memory _messageTwo,
uint _numberOne,
uint _numberTwo,
address _address
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_messageOne, _messageTwo, _numberOne, _numberTwo, _address));
}
function getEthSignedMessageHash(bytes32 _messageHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
);
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
internal
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory _sig)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(_sig.length == 65, "siglngth");
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
}
function verifySignature(
string memory _messageOne,
string memory _messageTwo,
uint _numberOne,
uint _numberTwo,
bytes memory signature
) internal view returns (bool) {
bytes32 _messageHash = getMessageHash(_messageOne, _messageTwo, _numberOne, _numberTwo, msg.sender);
bytes32 _ethSignedMessageHash = getEthSignedMessageHash(_messageHash);
return recoverSigner(_ethSignedMessageHash, signature) == verifySigner;
}
}
// Dependency file: contracts/imports/Withdraw.sol
/*
*
* Withdraw Contract
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* Withdraw funds from a contract
*
*/
// pragma solidity 0.8.9;
// import "@openzeppelin/contracts/access/Ownable.sol";
contract Withdraw is Ownable {
function seeBalance() public view onlyOwner returns(uint) {
return address(this).balance;
}
function withdraw(address payable _to, uint _amount) public onlyOwner returns(bool) {
require(_amount <= address(this).balance, "insfnds");
_to.transfer(_amount);
return true;
}
}
// Dependency file: contracts/imports/Group.sol
/*
*
* Group Contract
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* To be used in conjuction with VerifySignature as a way to validate a signature generated off-chain
*
*/
// pragma solidity 0.8.9;
// import "@openzeppelin/contracts/access/Ownable.sol";
contract Group is Ownable {
string public group = "init";
event GroupUpdated(string _group);
function setGroup(string memory _grp) public onlyOwner {
group = _grp;
emit GroupUpdated(_grp);
}
}
// Dependency file: contracts/imports/ExternalAccount.sol
/*
*
* ExternalAccount Contract
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* To be used to allow a single external address (likely another another contract) to interact with particular functions
*
*/
// pragma solidity 0.8.9;
// import "@openzeppelin/contracts/access/Ownable.sol";
contract ExternalAccount is Ownable {
address public externalAccount;
function setExternalAccount(address _addr) public onlyOwner {
externalAccount = _addr;
}
modifier onlyExternalAccount() {
require(externalAccount != address(0), "noext");
require(msg.sender == externalAccount, "invacct");
_;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
// import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
// import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_mint}.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual override {
super._mint(account, id, amount, data);
_totalSupply[id] += amount;
}
/**
* @dev See {ERC1155-_mintBatch}.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
/**
* @dev See {ERC1155-_burn}.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual override {
super._burn(account, id, amount);
_totalSupply[id] -= amount;
}
/**
* @dev See {ERC1155-_burnBatch}.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual override {
super._burnBatch(account, ids, amounts);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
// Dependency file: contracts/CabinetOfCuriosities.sol
/*
*
* Society of the Hourglass: Cabinet of Curiosities
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* Website: https://www.societyofthehourglass.com/
* Mint Page: https://app.hashku.com/team/society-of-the-hourglass/cabinet-of-curiosities/mint
*
*/
// pragma solidity 0.8.9;
// import "contracts/imports/VerifySignature.sol";
// import "contracts/imports/Withdraw.sol";
// import "contracts/imports/Group.sol";
// import "contracts/imports/ExternalAccount.sol";
// import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
// import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol";
// import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
contract CabinetOfCuriosities is
Ownable,
Withdraw,
Group,
VerifySignature,
ExternalAccount,
ERC1155,
ERC1155Burnable
{
mapping(uint256 => uint256) private _totalSupply;
struct CabinetItem {
uint256 price;
uint256 amountMinted;
uint256 amountAllowed;
uint256 maxMintPerAddress;
uint256 mainCollectionQty;
}
mapping(uint256 => CabinetItem) public items;
/// @notice How many items someone can mint
uint256 public maxMintEachAddress = 2;
mapping(address => uint) public hasMinted;
string private cabinetUri = "https://storage.hashku.com/api/soth/cabinet/{id}.json";
uint256 constant private DUST = 0;
uint256 constant private SCOPE = 1;
uint256 constant private BOOK = 2;
uint256 constant private BOT = 3;
uint256 constant private POSTER = 4;
uint256 constant private BOOK_CLOSED = 5;
uint256 constant private BOT_ACTIVE = 6;
uint256 public currentRaffleIndex = 11;
mapping(uint256 => bool) public nigelWinners;
constructor() ERC1155("https://storage.hashku.com/soth/cabinet/{id}.json") {
// forget me dust
items[DUST] = CabinetItem(60000000000000000, 0, 222, 2, 2);
// pocket spectroscope
items[SCOPE] = CabinetItem(120000000000000000, 0, 166, 2, 4);
// book of epochs
items[BOOK] = CabinetItem(170000000000000000, 0, 99, 2, 4);
// autotranslator bot
items[BOT] = CabinetItem(170000000000000000, 0, 99, 2, 4);
// wanted poster of nigel
items[POSTER] = CabinetItem(180000000000000000, 0, 99, 2, 4);
// opened book of epochs
items[BOOK_CLOSED] = CabinetItem(0, 0, 99, 2, 0);
// activated autotranslator bot
items[BOT_ACTIVE] = CabinetItem(0, 0, 99, 2, 0);
// Raffle tickets will be IDs 11-99
}
/*
* @notice Total supply of a given item
*/
function totalSupply(uint256 id) public view returns (uint256) {
return _totalSupply[id];
}
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal override {
super._mint(account, id, amount, data);
_totalSupply[id] += amount;
}
function _burn(
address account,
uint256 id,
uint256 amount
) internal override {
super._burn(account, id, amount);
_totalSupply[id] -= amount;
}
/*
* @notice Set overall quanitity a user is allowed to mint
*/
function setMaxMintEachAddress(uint256 _amt) public onlyOwner {
maxMintEachAddress = _amt;
}
/*
* @notice Set a Nigel raffle ticket as a winner
*/
function setNigelWinner(uint256 _id) public onlyOwner {
nigelWinners[_id] = true;
}
/*
* @notice Allow updating the item data
*/
function setItem( uint256 _id, uint256 _price, uint256 _amountAllowed, uint256 _maxMintPerAddress, uint256 _mainCollectionQty ) public onlyOwner {
items[_id].price = _price;
items[_id].amountAllowed = _amountAllowed;
items[_id].maxMintPerAddress = _maxMintPerAddress;
items[_id].mainCollectionQty = _mainCollectionQty;
}
function uri(uint256) public view override returns (string memory) {
return cabinetUri;
}
function setURI(string memory _newuri) public onlyOwner {
cabinetUri = _newuri;
}
/*
* @notice Shop for a single item of varyiable quantity
*/
function shop( uint256 _id, uint256 _qty, bytes memory _signature ) public payable {
// check signature - will be provided by Hashku
require(verifySignature("SHOP", group, _id, _qty, _signature), "invsig");
require(_id < 5, "invitm");
require(_qty * items[_id].price == msg.value, "incfnds");
mintInternal(msg.sender, _id, _qty);
}
/*
* @notice Shop for more than a single item
*/
function shopMultiple( uint256[] memory _ids, uint256[] memory _qtys, bytes memory _signature ) public payable {
// check signature - will be provided by Hashku
require(verifySignature("SHOP", group, _ids[0], _qtys[0], _signature), "invsig");
require(_ids.length == _qtys.length, "idqtymm");
require(_ids.length < 6, "maxitms");
uint256 _totalPrice;
for (uint256 _i = 0; _i < _ids.length; _i++) {
require(_ids[_i] < 5, "invitm");
_totalPrice += items[_ids[_i]].price * _qtys[_i];
}
require(_totalPrice == msg.value, "incfnds");
for (uint256 _i = 0; _i < _ids.length; _i++) {
mintInternal(msg.sender, _ids[_i], _qtys[_i]);
}
}
/*
* @notice Mint an item, used by other functions only
*/
function mintInternal(address _to, uint256 _id, uint256 _qty) internal {
require(hasMinted[_to] + _qty <= maxMintEachAddress, "mintmax");
require(items[_id].amountMinted + _qty <= items[_id].amountAllowed, "itmunv");
require(_qty + balanceOf(_to, _id) <= items[_id].maxMintPerAddress, "itmmax");
hasMinted[_to] += _qty;
items[_id].amountMinted += _qty;
_mint(_to, _id, _qty, "");
}
/*
* @notice Send tokens to an address (to be used for rewarding community members and partners)
*/
function send(address _to, uint256[] memory _ids, uint256[] memory _qtys) public onlyOwner {
require(_ids.length == _qtys.length, "idqtymm");
require(_ids.length < 6, "maxitms");
for (uint256 _i = 0; _i < _ids.length; _i++) {
require(_ids[_i] < 5, "invitm");
}
for (uint256 _i = 0; _i < _ids.length; _i++) {
mintInternal(_to, _ids[_i], _qtys[_i]);
}
}
/*
* @notice Mint BOOK_CLOSED or BOT_ACTIVE from redemption contract
*/
function mintExternal(address _to, uint256 _id, uint256 _qty) external onlyExternalAccount {
require(_id > 4, "invitm");
require(_id < 7, "invitm");
items[_id].amountMinted += _qty;
_mint(_to, _id, _qty, "");
}
/*
* @notice Mint Nigel raffle ticket (IDs 11+)
*/
function mintNigelRaffle(address _to, uint256 _qty) external onlyExternalAccount {
for (uint256 _i = 0; _i < _qty; _i++) {
_mint(_to, currentRaffleIndex, 1, "");
currentRaffleIndex += 1;
}
}
/*
* @notice Burn token from redemption account
*/
function burnExternal(address _to, uint256 _id, uint256 _qty) external onlyExternalAccount {
_burn(_to, _id, _qty);
}
/*
* @notice Shortcut for retrieving number of main collection NFTs are redemeed from a Cabinet item
*/
function itemMainCollectionQuantity(uint256 _id) public view returns (uint256) {
return items[_id].mainCollectionQty;
}
function burn(
address _account,
uint256 _id,
uint256 _value
) override public virtual onlyOwner {}
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _values
) override public virtual onlyOwner {}
}
// Dependency file: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// Root file: contracts/SocietyOfTheHourglass.sol
pragma solidity 0.8.9;
/*
*
* Society of the Hourglass: Main Collection + Cabinet of Curiosities Redemption
*
* Contract by Matt Casanova [Twitter: @DevGuyThings]
*
* Website: https://www.societyofthehourglass.com/
* Mint Page: https://app.hashku.com/team/society-of-the-hourglass/main/mint
*
*/
// import "contracts/Hashku.sol";
// import "contracts/CabinetOfCuriosities.sol";
// import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
// import "@openzeppelin/contracts/utils/Strings.sol";
contract SocietyOfTheHourglass is Hashku, ERC721Holder {
using Strings for uint256;
// total main collection tokens based on 2022-01-01 cabinet items; will decrease as cabinet items are redeemed
uint256 public reservedFromCabinet = 642;
// mapping of which tokens have a bot
mapping(uint256 => bool) public hasBot;
// mappig of which tokens are in the book
mapping(uint256 => bool) public inBook;
// track which nigel token will mint next
uint256 public nextNigelIndex;
// how many nigels total
uint256 constant private nigelsAvailable = 10;
constructor() Hashku(
"Society of the Hourglass",
"SOTH",
"https://storage.hashku.com/api/soth/main/",
"SOTH",
8888,
20,
30,
70000000000000000,
5,
0xED0998a1489Ab5cF1900f546f620aB67Af19915B
) {
// on deploy, mint the first 10 tokens to the contract
// these first ten tokens are nigels
for (uint256 i = 0; i < nigelsAvailable; i++) {
mint(address(this));
}
}
// set however many tokens should be reserved for cabinet redemption
function setReservedFromCabinet(uint256 _amt) public onlyOwner {
require(nextToken() + _amt <= maxTokens, "too_many");
reservedFromCabinet = _amt;
}
// owner can ONLY decrease the total number of available tokens
function decreaseMaxTokens(uint256 _amount) external override onlyOwner {
require(_amount < maxTokens, "only_decrease");
require(_amount > reservedFromCabinet + nextToken(), "cabinet_reserved");
maxTokens = _amount;
}
// internal function for transferring a nigel
function transferNigel(address _to) internal {
// nigels will be 0-9, nigelsAvailable will be 10
require(nextNigelIndex + 1 < nigelsAvailable, "none_available");
uint256 nigelIdToClaim = nextNigelIndex;
nextNigelIndex += 1;
_safeTransfer(address(this), _to, nigelIdToClaim, "");
delete nigelIdToClaim;
}
// internal function for setting bot on a token
function setHasBot(uint256 _tokenId) internal {
require(!hasBot[_tokenId], "already_has_bot");
hasBot[_tokenId] = true;
}
// internal function for marking a token in the book
function setIsInBook(uint256 _tokenId) internal {
require(!inBook[_tokenId], "already_has_bot");
inBook[_tokenId] = true;
}
// once final tokens are set and we know all tokens to be in book, will call this to update the contract
function setIsInBookMultiple(uint256[] calldata _tokenIds) external onlyOwner {
for (uint256 i = 0; i < _tokenIds.length; i++) {
setIsInBook(_tokenIds[i]);
}
}
// returns uri with data for book and bot where appropriate
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "no_token");
string memory append = ".json?var=1";
string memory addBot = "";
if (hasBot[_tokenId]) {
addBot = "&bot=yes";
}
string memory addBook = "";
if (inBook[_tokenId]) {
addBook = "&book=yes";
}
return bytes(baseTokenURI).length > 0 ? string(abi.encodePacked(baseTokenURI, _tokenId.toString(), append, addBot, addBook)) : "";
}
// buy NFTs - version without signature required for public mint
function shop(uint256 _amount) external override payable {
require(nextToken() + _amount + reservedFromCabinet <= maxTokens, "sold_out");
require(_amount <= maxMintPerTransaction, "max_mintable");
require(!isClosed, "is_closed");
require(isPublic, "not_public");
require(price * _amount == msg.value, "incorrect_funds");
for (uint256 i = 0; i < _amount; i++) {
mint(_msgSender());
}
}
// buy NFTs - signature required from Hashku for presale
function shop(uint256 _amount, bytes memory _signature) external override payable {
require(nextToken() + _amount + reservedFromCabinet <= maxTokens, "sold_out");
require(tokensMinted[_msgSender()] + _amount <= maxMintPerAddress, "max_minted");
require(!isClosed, "is_closed");
require(verifySignature(_signature), "invalid_signature");
require(price * _amount == msg.value, "incorrect_funds");
tokensMinted[_msgSender()] += _amount;
for (uint256 i = 0; i < _amount; i++) {
mint(_msgSender());
}
}
// owner sends NFTs to addresses
function send(address[] calldata _addresses, uint256[] calldata _amounts) external override onlyOwner {
require(_addresses.length == _amounts.length, "amount_mismatch");
uint256 total;
for (uint256 t = 0; t < _amounts.length; t++) {
total += _amounts[t];
}
require(nextToken() + total + reservedFromCabinet <= maxTokens, "sold_out");
delete total;
for (uint256 i = 0; i < _addresses.length; i++) {
for (uint256 a = 0; a < _amounts[i]; a++) {
mint(_addresses[i]);
}
}
}
// cabinet collection address
CabinetOfCuriosities public externalAccount;
// redemption of initial cabinet items allowed when true
bool public redemptionOpen;
// redemption of secondary cabinet items allowed when true
bool public secondRedemptionOpen;
modifier cabinetMustBeSet() {
require(address(externalAccount) != address(0), "no_cabinet");
_;
}
// open or close initial cabinet item redemption
function setRedemptionOpen(bool _open) public onlyOwner {
redemptionOpen = _open;
}
// open or close secondary cabinet item redemption
function setSecondRedemptionOpen(bool _open) public onlyOwner {
secondRedemptionOpen = _open;
}
// set the cabinet account
function setExternalAccount(address _contract) public onlyOwner {
externalAccount = CabinetOfCuriosities(_contract);
}
// external function to mint Nigel raffle tickets in case we have external awards or later uses for raffle tickets
function mintNigelRaffle(address _to, uint256 _qty) external onlyOwner cabinetMustBeSet {
externalAccount.mintNigelRaffle(_to, _qty);
}
// redeem a winning nigel raffle ticket from the cabinet
function useNigelTicket(uint256 _id) public cabinetMustBeSet {
require(secondRedemptionOpen, "not_open");
require(externalAccount.nigelWinners(_id), "not_winner");
require(externalAccount.balanceOf(msg.sender, _id) >= 1, "not_enough");
// burn nigel ticket
externalAccount.burnExternal(msg.sender, _id, 1);
// mint a nigel from the main collection
transferNigel(msg.sender);
}
// check that the msg sender is the owner of an array of tokens
function validateOwner(uint[] calldata _tokenIds) internal view returns (bool) {
for (uint256 _i = 0; _i < _tokenIds.length; _i++) {
// does the user own the tokenIds
require(ownerOf(_tokenIds[_i]) == msg.sender, "not_owner");
}
return true;
}
// assign bots to main collection tokens
function useBot(uint[] calldata _tokenIds) public cabinetMustBeSet {
require(secondRedemptionOpen, "not_open");
require(externalAccount.balanceOf(msg.sender, 6) >= _tokenIds.length, "no_item");
validateOwner(_tokenIds);
externalAccount.burnExternal(msg.sender, 6, _tokenIds.length);
for (uint256 _i = 0; _i < _tokenIds.length; _i++) {
setHasBot(_tokenIds[_i]);
}
}
// assign books to main collection tokens
function useBook(uint[] calldata _tokenIds) public cabinetMustBeSet {
require(secondRedemptionOpen, "not_open");
require(externalAccount.balanceOf(msg.sender, 5) >= _tokenIds.length, "no_item");
validateOwner(_tokenIds);
externalAccount.burnExternal(msg.sender, 5, _tokenIds.length);
for (uint256 _i = 0; _i < _tokenIds.length; _i++) {
setIsInBook(_tokenIds[_i]);
}
}
// redeem items from the cabinet of curiosities
function redeem(uint[] calldata _itemIds, uint[] calldata _itemQtys) public cabinetMustBeSet {
require(redemptionOpen, "not_open");
require(_itemIds.length > 0, "no_items");
require(_itemIds.length == _itemQtys.length, "length_mismatch");
require(_itemIds.length < 6, "invalid_items");
for (uint256 _i = 0; _i < _itemIds.length; _i++) {
require(_itemQtys[_i] > 0, "quantity_zero");
// does the user own enough tokenIds
require(externalAccount.balanceOf(msg.sender, _itemIds[_i]) >= _itemQtys[_i], "no_item");
require(_itemIds[_i] < 5, "invalid_item");
}
uint256 _qtyMintMain;
for (uint256 _i = 0; _i < _itemIds.length; _i++) {
// burn the number of tokens by id
externalAccount.burnExternal(msg.sender, _itemIds[_i], _itemQtys[_i]);
// each token gets at least 1 from main collection
_qtyMintMain += externalAccount.itemMainCollectionQuantity(_itemIds[_i]) * _itemQtys[_i];
// book, bot, and poster get an additional item minted
if (_itemIds[_i] == 2) {
externalAccount.mintExternal(msg.sender, 5, _itemQtys[_i]);
} else if (_itemIds[_i] == 3) {
externalAccount.mintExternal(msg.sender, 6, _itemQtys[_i]);
} else if (_itemIds[_i] == 4) {
externalAccount.mintNigelRaffle(msg.sender, _itemQtys[_i]);
}
}
reservedFromCabinet -= _qtyMintMain;
// finally mint all the correct qty
for (uint256 i = 0; i < _qtyMintMain; i++) {
mint(msg.sender);
}
}
}
|
set the maximum amount an address may mint
|
function setMaxMintPerAddress(uint256 _amount) external virtual onlyOwner {
maxMintPerAddress = _amount;
}
| 7,927,188
|
./partial_match/1/0x7389D9712E4CF8Ed5ae22b9ee21CE42cE2e3f050/sources/src/contracts/FXB.sol
|
Returns summary information about the bond return BondInfo Summary of the bond
|
function bondInfo() external view returns (BondInfo memory) {
}
| 4,411,012
|
./full_match/80001/0xB4cb47bc9C7c7E49d742EB032D8BafD377Be1f31/sources/contracts/MainVault.sol
|
Setter for new game address _game New address of the game
|
function setGame(address _game) external onlyDao {
game = _game;
}
| 5,564,022
|
pragma solidity ^0.4.25;
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);
}
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);
}
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || 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;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => bool) blockListed;
/**
* @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(
balances[msg.sender] >= _value
&& _value > 0
&& !blockListed[_to]
&& !blockListed[msg.sender]
);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(
_to != address(0)
&& balances[msg.sender] >= _value
&& balances[_from] >= _value
&& _value > 0
&& !blockListed[_to]
&& !blockListed[msg.sender]
);
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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 remaining) {
return allowed[_owner][_spender];
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
}
contract Ownable {
address internal 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() 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) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function addBlockeddUser(address user) public onlyOwner {
blockListed[user] = true;
}
function removeBlockeddUser(address user) public onlyOwner {
blockListed[user] = false;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
}
contract AutoCoinToken is MintableToken {
/**
* @string name - Token Name
* @string symbol - Token Symbol
* @uint8 decimals - Token Decimals
* @uint256 _totalSupply - Token Total Supply
*/
string public constant name = "AUTO COIN";
string public constant symbol = "AUTO COIN";
uint8 public constant decimals = 18;
uint256 public constant _totalSupply = 400000000000000000000000000;
/** Constructor AutoCoinToken */
constructor() public {
totalSupply = _totalSupply;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Crowdsale is Ownable, Pausable {
using SafeMath for uint256;
/**
* @MintableToken token - Token Object
* @address wallet - Wallet Address
* @uint8 rate - Tokens per Ether
* @uint256 weiRaised - Total funds raised in Ethers
*/
MintableToken internal token;
address internal wallet;
uint256 public rate;
uint256 internal weiRaised;
/**
* @uint256 privateSaleStartTime - Private-Sale Start Time
* @uint256 privateSaleEndTime - Private-Sale End Time
* @uint256 preSaleStartTime - Pre-Sale Start Time
* @uint256 preSaleEndTime - Pre-Sale End Time
* @uint256 preICOStartTime - Pre-ICO Start Time
* @uint256 preICOEndTime - Pre-ICO End Time
* @uint256 ICOstartTime - ICO Start Time
* @uint256 ICOEndTime - ICO End Time
*/
uint256 public privateSaleStartTime;
uint256 public privateSaleEndTime;
uint256 public preSaleStartTime;
uint256 public preSaleEndTime;
uint256 public preICOStartTime;
uint256 public preICOEndTime;
uint256 public ICOstartTime;
uint256 public ICOEndTime;
/**
* @uint privateBonus - Private Bonus
* @uint preSaleBonus - Pre-Sale Bonus
* @uint preICOBonus - Pre-Sale Bonus
* @uint firstWeekBonus - ICO 1st Week Bonus
* @uint secondWeekBonus - ICO 2nd Week Bonus
* @uint thirdWeekBonus - ICO 3rd Week Bonus
* @uint forthWeekBonus - ICO 4th Week Bonus
* @uint fifthWeekBonus - ICO 5th Week Bonus
*/
uint256 internal privateSaleBonus;
uint256 internal preSaleBonus;
uint256 internal preICOBonus;
uint256 internal firstWeekBonus;
uint256 internal secondWeekBonus;
uint256 internal thirdWeekBonus;
uint256 internal forthWeekBonus;
uint256 internal fifthWeekBonus;
uint256 internal weekOne;
uint256 internal weekTwo;
uint256 internal weekThree;
uint256 internal weekFour;
uint256 internal weekFive;
uint256 internal privateSaleTarget;
uint256 internal preSaleTarget;
uint256 internal preICOTarget;
/**
* @uint256 totalSupply - Total supply of tokens
* @uint256 publicSupply - Total public Supply
* @uint256 bountySupply - Total Bounty Supply
* @uint256 reservedSupply - Total Reserved Supply
* @uint256 privateSaleSupply - Total Private Supply from Public Supply
* @uint256 preSaleSupply - Total PreSale Supply from Public Supply
* @uint256 preICOSupply - Total PreICO Supply from Public Supply
* @uint256 icoSupply - Total ICO Supply from Public Supply
*/
uint256 public totalSupply = SafeMath.mul(400000000, 1 ether);
uint256 internal publicSupply = SafeMath.mul(SafeMath.div(totalSupply,100),55);
uint256 internal bountySupply = SafeMath.mul(SafeMath.div(totalSupply,100),6);
uint256 internal reservedSupply = SafeMath.mul(SafeMath.div(totalSupply,100),39);
uint256 internal privateSaleSupply = SafeMath.mul(24750000, 1 ether);
uint256 internal preSaleSupply = SafeMath.mul(39187500, 1 ether);
uint256 internal preICOSupply = SafeMath.mul(39187500, 1 ether);
uint256 internal icoSupply = SafeMath.mul(116875000, 1 ether);
/**
* @bool checkUnsoldTokens - Tokens will be added to bounty supply
* @bool upgradePreSaleSupply - Boolean variable updates when the PrivateSale tokens added to PreSale supply
* @bool upgradePreICOSupply - Boolean variable updates when the PreSale tokens added to PreICO supply
* @bool upgradeICOSupply - Boolean variable updates when the PreICO tokens added to ICO supply
* @bool grantFounderTeamSupply - Boolean variable updates when Team and Founder tokens minted
*/
bool public checkUnsoldTokens;
bool internal upgradePreSaleSupply;
bool internal upgradePreICOSupply;
bool internal upgradeICOSupply;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value Wei's paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* function Crowdsale - Parameterized Constructor
* @param _startTime - StartTime of Crowdsale
* @param _endTime - EndTime of Crowdsale
* @param _rate - Tokens against Ether
* @param _wallet - MultiSignature Wallet Address
*/
constructor(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) internal {
require(_wallet != 0x0);
token = createTokenContract();
privateSaleStartTime = _startTime;
privateSaleEndTime = 1537952399;
preSaleStartTime = 1537952400;
preSaleEndTime = 1541581199;
preICOStartTime = 1541581200;
preICOEndTime = 1544000399;
ICOstartTime = 1544000400;
ICOEndTime = _endTime;
rate = _rate;
wallet = _wallet;
privateSaleBonus = SafeMath.div(SafeMath.mul(rate,50),100);
preSaleBonus = SafeMath.div(SafeMath.mul(rate,30),100);
preICOBonus = SafeMath.div(SafeMath.mul(rate,30),100);
firstWeekBonus = SafeMath.div(SafeMath.mul(rate,20),100);
secondWeekBonus = SafeMath.div(SafeMath.mul(rate,15),100);
thirdWeekBonus = SafeMath.div(SafeMath.mul(rate,10),100);
forthWeekBonus = SafeMath.div(SafeMath.mul(rate,5),100);
weekOne = SafeMath.add(ICOstartTime, 14 days);
weekTwo = SafeMath.add(weekOne, 14 days);
weekThree = SafeMath.add(weekTwo, 14 days);
weekFour = SafeMath.add(weekThree, 14 days);
weekFive = SafeMath.add(weekFour, 14 days);
privateSaleTarget = SafeMath.mul(4500, 1 ether);
preSaleTarget = SafeMath.mul(7125, 1 ether);
preICOTarget = SafeMath.mul(7125, 1 ether);
checkUnsoldTokens = false;
upgradeICOSupply = false;
upgradePreICOSupply = false;
upgradePreSaleSupply = false;
}
/**
* function createTokenContract - Mintable Token Created
*/
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
/**
* function Fallback - Receives Ethers
*/
function () payable public {
buyTokens(msg.sender);
}
/**
* function preSaleTokens - Calculate Tokens in PreSale
*/
function privateSaleTokens(uint256 weiAmount, uint256 tokens) internal returns (uint256) {
require(privateSaleSupply > 0);
require(weiAmount <= privateSaleTarget);
tokens = SafeMath.add(tokens, weiAmount.mul(privateSaleBonus));
tokens = SafeMath.add(tokens, weiAmount.mul(rate));
require(privateSaleSupply >= tokens);
privateSaleSupply = privateSaleSupply.sub(tokens);
privateSaleTarget = privateSaleTarget.sub(weiAmount);
return tokens;
}
/**
* function preSaleTokens - Calculate Tokens in PreSale
*/
function preSaleTokens(uint256 weiAmount, uint256 tokens) internal returns (uint256) {
require(preSaleSupply > 0);
require(weiAmount <= preSaleTarget);
if (!upgradePreSaleSupply) {
preSaleSupply = SafeMath.add(preSaleSupply, privateSaleSupply);
preSaleTarget = SafeMath.add(preSaleTarget, privateSaleTarget);
upgradePreSaleSupply = true;
}
tokens = SafeMath.add(tokens, weiAmount.mul(preSaleBonus));
tokens = SafeMath.add(tokens, weiAmount.mul(rate));
require(preSaleSupply >= tokens);
preSaleSupply = preSaleSupply.sub(tokens);
preSaleTarget = preSaleTarget.sub(weiAmount);
return tokens;
}
/**
* function preICOTokens - Calculate Tokens in PreICO
*/
function preICOTokens(uint256 weiAmount, uint256 tokens) internal returns (uint256) {
require(preICOSupply > 0);
require(weiAmount <= preICOTarget);
if (!upgradePreICOSupply) {
preICOSupply = SafeMath.add(preICOSupply, preSaleSupply);
preICOTarget = SafeMath.add(preICOTarget, preSaleTarget);
upgradePreICOSupply = true;
}
tokens = SafeMath.add(tokens, weiAmount.mul(preICOBonus));
tokens = SafeMath.add(tokens, weiAmount.mul(rate));
require(preICOSupply >= tokens);
preICOSupply = preICOSupply.sub(tokens);
preICOTarget = preICOTarget.sub(weiAmount);
return tokens;
}
/**
* function icoTokens - Calculate Tokens in ICO
*/
function icoTokens(uint256 weiAmount, uint256 tokens, uint256 accessTime) internal returns (uint256) {
require(icoSupply > 0);
if (!upgradeICOSupply) {
icoSupply = SafeMath.add(icoSupply,preICOSupply);
upgradeICOSupply = true;
}
if (accessTime <= weekOne) {
tokens = SafeMath.add(tokens, weiAmount.mul(firstWeekBonus));
} else if (accessTime <= weekTwo) {
tokens = SafeMath.add(tokens, weiAmount.mul(secondWeekBonus));
} else if ( accessTime < weekThree ) {
tokens = SafeMath.add(tokens, weiAmount.mul(thirdWeekBonus));
} else if ( accessTime < weekFour ) {
tokens = SafeMath.add(tokens, weiAmount.mul(forthWeekBonus));
} else if ( accessTime < weekFive ) {
tokens = SafeMath.add(tokens, weiAmount.mul(fifthWeekBonus));
}
tokens = SafeMath.add(tokens, weiAmount.mul(rate));
icoSupply = icoSupply.sub(tokens);
return tokens;
}
/**
* function buyTokens - Collect Ethers and transfer tokens
*/
function buyTokens(address beneficiary) whenNotPaused internal {
require(beneficiary != 0x0);
require(validPurchase());
uint256 accessTime = now;
uint256 tokens = 0;
uint256 weiAmount = msg.value;
require((weiAmount >= (100000000000000000)) && (weiAmount <= (20000000000000000000)));
if ((accessTime >= privateSaleStartTime) && (accessTime < privateSaleEndTime)) {
tokens = privateSaleTokens(weiAmount, tokens);
} else if ((accessTime >= preSaleStartTime) && (accessTime < preSaleEndTime)) {
tokens = preSaleTokens(weiAmount, tokens);
} else if ((accessTime >= preICOStartTime) && (accessTime < preICOEndTime)) {
tokens = preICOTokens(weiAmount, tokens);
} else if ((accessTime >= ICOstartTime) && (accessTime <= ICOEndTime)) {
tokens = icoTokens(weiAmount, tokens, accessTime);
} else {
revert();
}
publicSupply = publicSupply.sub(tokens);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
/**
* function forwardFunds - Transfer funds to wallet
*/
function forwardFunds() internal {
wallet.transfer(msg.value);
}
/**
* function validPurchase - Checks the purchase is valid or not
* @return true - Purchase is withPeriod and nonZero
*/
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= privateSaleStartTime && now <= ICOEndTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
/**
* function hasEnded - Checks the ICO ends or not
* @return true - ICO Ends
*/
function hasEnded() public view returns (bool) {
return now > ICOEndTime;
}
/**
* function unsoldToken - Function used to transfer all
* unsold public tokens to reserve supply
*/
function unsoldToken() onlyOwner public {
require(hasEnded());
require(!checkUnsoldTokens);
checkUnsoldTokens = true;
bountySupply = SafeMath.add(bountySupply, publicSupply);
publicSupply = 0;
}
/**
* function getTokenAddress - Get Token Address
*/
function getTokenAddress() onlyOwner view public returns (address) {
return token;
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
return super.validPurchase() && weiRaised.add(msg.value) <= cap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return super.hasEnded() || weiRaised >= cap;
}
}
contract CrowdsaleFunctions is Crowdsale {
/**
* function bountyFunds - Transfer bounty tokens via AirDrop
* @param beneficiary address where owner wants to transfer tokens
* @param tokens value of token
*/
function bountyFunds(address[] beneficiary, uint256[] tokens) public onlyOwner {
for (uint256 i = 0; i < beneficiary.length; i++) {
tokens[i] = SafeMath.mul(tokens[i],1 ether);
require(beneficiary[i] != 0x0);
require(bountySupply >= tokens[i]);
bountySupply = SafeMath.sub(bountySupply,tokens[i]);
token.mint(beneficiary[i], tokens[i]);
}
}
/**
* function grantReservedToken - Transfer advisor,team and founder tokens
*/
function grantReservedToken(address beneficiary, uint256 tokens) public onlyOwner {
require(beneficiary != 0x0);
require(reservedSupply > 0);
tokens = SafeMath.mul(tokens,1 ether);
require(reservedSupply >= tokens);
reservedSupply = SafeMath.sub(reservedSupply,tokens);
token.mint(beneficiary, tokens);
}
/**
*.function transferToken - Used to transfer tokens to investors who pays us other than Ethers
* @param beneficiary - Address where owner wants to transfer tokens
* @param tokens - Number of tokens
*/
function transferToken(address beneficiary, uint256 tokens) onlyOwner public {
require(beneficiary != 0x0);
require(publicSupply > 0);
tokens = SafeMath.mul(tokens,1 ether);
require(publicSupply >= tokens);
publicSupply = SafeMath.sub(publicSupply,tokens);
token.mint(beneficiary, tokens);
}
function addBlockListed(address user) public onlyOwner {
token.addBlockeddUser(user);
}
function removeBlockListed(address user) public onlyOwner {
token.removeBlockeddUser(user);
}
}
contract FinalizableCrowdsale is Crowdsale {
using SafeMath for uint256;
bool isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal view {
}
}
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 public goal;
bool private _goalReached = false;
// refund vault used to hold funds while crowdsale is running
RefundVault private vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal view {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public payable returns (bool) {
if (weiRaised >= goal) {
_goalReached = true;
return true;
} else if (_goalReached) {
return true;
}
else {
return false;
}
}
function updateGoalCheck() onlyOwner public {
_goalReached = true;
}
function getVaultAddress() onlyOwner view public returns (address) {
return vault;
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address _wallet) public {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
|
Burns a specific amount of tokens. _value The amount of token to be burned./
|
function burn(uint256 _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
| 2,543,612
|
pragma solidity ^0.4.18;
interface token {
function transferFrom(address _from, address _to, uint256 _value) public;
}
contract RetailSale {
address public beneficiary;
uint public actualPrice;
uint public nextPrice;
uint public nextPriceDate = 0;
uint public periodStart;
uint public periodEnd;
uint public bonus = 0;
uint public bonusStart = 0;
uint public bonusEnd = 0;
uint public milestone = 0;
uint public milestoneBonus = 0;
bool public milestoneReached = true;
uint public minPurchase;
token public tokenReward;
event FundTransfer(address backer, uint amount, uint bonus, uint tokens);
/**
* Constrctor function
*
* Setup the owner
*/
function RetailSale(
address _beneficiary,
address addressOfTokenUsedAsReward,
uint ethPriceInWei,
uint _minPurchase,
uint start,
uint end
) public {
beneficiary = _beneficiary;
tokenReward = token(addressOfTokenUsedAsReward);
actualPrice = ethPriceInWei;
nextPrice = ethPriceInWei;
minPurchase = _minPurchase;
periodStart = start;
periodEnd = end;
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function()
payable
isOpen
aboveMinValue
public {
uint price = actualPrice;
if (now >= nextPriceDate) {
price = nextPrice;
}
uint vp = (msg.value * 1 ether) / price;
uint b = 0;
uint tokens = 0;
if (now >= bonusStart && now <= bonusEnd) {
b = bonus;
}
if (this.balance >= milestone && !milestoneReached) {
b = milestoneBonus;
milestoneReached = true;
}
if (b == 0) {
tokens = vp;
} else {
tokens = (vp + ((vp * b) / 100));
}
tokenReward.transferFrom(beneficiary, msg.sender, tokens);
FundTransfer(msg.sender, msg.value, b, tokens);
}
modifier aboveMinValue() {
require(msg.value >= minPurchase);
_;
}
modifier isOwner() {
require(msg.sender == beneficiary);
_;
}
modifier isClosed() {
require(!(now >= periodStart && now <= periodEnd));
_;
}
modifier isOpen() {
require(now >= periodStart && now <= periodEnd);
_;
}
modifier validPeriod(uint start, uint end){
require(start < end);
_;
}
/**
* Set next start date
* @param _start the next start date in seconds.
* @param _start the next end date in seconds.
*/
function setNextPeriod(uint _start, uint _end)
isOwner
validPeriod(_start, _end)
public {
periodStart = _start;
periodEnd = _end;
}
/**
* Set the new min purchase value
* @param _minPurchase the new minpurchase value in wei.
*/
function setMinPurchase(uint _minPurchase)
isOwner
public {
minPurchase = _minPurchase;
}
/**
* Change the bonus percentage
* @param _bonus the new bonus percentage.
* @param _bonusStart When the bonus starts in seconds.
* @param _bonusEnd When the bonus ends in seconds.
*/
function changeBonus(uint _bonus, uint _bonusStart, uint _bonusEnd)
isOwner
public {
bonus = _bonus;
bonusStart = _bonusStart;
bonusEnd = _bonusEnd;
}
/**
* Change the next milestone
* @param _milestone The next milestone amount in wei
* @param _milestoneBonus The bonus of the next milestone
*/
function setNextMilestone(uint _milestone, uint _milestoneBonus)
isOwner
public {
milestone = _milestone;
milestoneBonus = _milestoneBonus;
milestoneReached = false;
}
/**
* Set the next price
* @param _price The next eth price in wei
* @param _priceDate The date in second when the next price start
*/
function setNextPrice(uint _price, uint _priceDate)
isOwner
public {
actualPrice = nextPrice;
nextPrice = _price;
nextPriceDate = _priceDate;
}
/**
* Withdraw the funds
*
* Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
* sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal()
isClosed
isOwner
public {
beneficiary.transfer(this.balance);
}
function open() view public returns (bool) {
return (now >= periodStart && now <= periodEnd);
}
}
|
Fallback function The function without name is the default function that is called whenever anyone sends funds to a contract/
|
function()
payable
isOpen
aboveMinValue
public {
uint price = actualPrice;
if (now >= nextPriceDate) {
price = nextPrice;
}
uint vp = (msg.value * 1 ether) / price;
uint b = 0;
uint tokens = 0;
if (now >= bonusStart && now <= bonusEnd) {
b = bonus;
}
if (this.balance >= milestone && !milestoneReached) {
b = milestoneBonus;
milestoneReached = true;
}
if (b == 0) {
tokens = vp;
tokens = (vp + ((vp * b) / 100));
}
tokenReward.transferFrom(beneficiary, msg.sender, tokens);
FundTransfer(msg.sender, msg.value, b, tokens);
}
| 373,613
|
./partial_match/1/0xd3F0A0DcB83A4a82a4fEBAaC65212fE74CA6461E/sources/DragonNewBorn.sol
|
if any account belongs to _isExcludedFromFee account then remove the fee
|
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "Blacklisted address");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if (from == uniswapV2Pair) {
require (_lastBuy[to] + _buyCooldown < block.timestamp, "Must wait til after coooldown to buy");
_lastBuy[to] = block.timestamp;
}
if (balanceOf(address(this)) >= SWAP_TOKENS_AT_AMOUNT && !swapping && from != uniswapV2Pair && from != owner() && to != owner()) {
swapping = true;
swapAndLiquify();
uint256 sellTokens = balanceOf(address(this));
swapAndSendToFee(sellTokens);
swapping = false;
}
_tOwned[from] -= amount;
uint256 transferAmount = amount;
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
transferAmount = _getValues(amount, from);
}
_tOwned[to] += transferAmount;
emit Transfer(from, to, transferAmount);
}
| 2,760,488
|
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/OrderValidator.sol
|
Internal pure function to check whether a given order type indicates that partial fills are not supported (e.g. only "full fills" are allowed for the order in question). orderType The order type in question. numerator The numerator in question. denominator The denominator in question. return isFullOrder A boolean indicating whether the order type only supports full fills./ The "full" order types are even, while "partial" order types are odd. Bitwise and by 1 is equivalent to modulo by 2, but 2 gas cheaper. The check is only necessary if numerator is less than denominator.
|
{
function _doesNotSupportPartialFills(OrderType orderType, uint256 numerator, uint256 denominator)
internal
pure
returns (bool isFullOrder)
assembly {
isFullOrder := and(lt(numerator, denominator), iszero(and(orderType, 1)))
}
}
| 9,676,086
|
/*
MIT License
Copyright (c) 2017 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity ^0.4.6;
import "oraclizeLib.sol";
import "FixedToDynamic.sol";
import "idOracleLib.sol";
contract OraclesPipeAPI {
function sendPipe(bytes _pipe) external;
}
contract DigitalIdConnector {
address public owner_;
address public database_; //permanent
address public logic_;
address public oracle_;
address public walletOracle_;
address public interface_;
address public coster_;
modifier onlyOwner() { if (msg.sender != owner_) throw; _; }
event LOG_updatedDatabase(address indexed addr);
event LOG_updatedLogic(address indexed addr);
event LOG_updatedOracle(address indexed addr);
event LOG_updatedWalletOracle(address indexed addr);
event LOG_updatedInterface(address indexed addr);
event LOG_updatedCostEstimator(address indexed addr);
function DigitalIdConnector() {
owner_ = msg.sender;
}
function updateDatabaseAddress(address _database)
external
onlyOwner {
database_ = _database;
LOG_updatedDatabase(_database);
}
function updateLogicAddress(address _logic)
external
onlyOwner {
logic_ = _logic;
LOG_updatedLogic(_logic);
}
function updateOracleAddress(address _oracle)
external
onlyOwner {
oracle_ = _oracle;
LOG_updatedOracle(_oracle);
}
function updateWalletOracleAddress(address _walletOracle)
external
onlyOwner {
walletOracle_ = _walletOracle;
LOG_updatedWalletOracle(_walletOracle);
}
function updateInterfaceAddress(address _interface)
external
onlyOwner {
interface_ = _interface;
LOG_updatedInterface(_interface);
}
function updateCosterAddress(address _coster)
external
onlyOwner {
coster_ = _coster;
LOG_updatedInterface(_coster);
}
}
contract DigitalIdInterface {
DigitalIdConnector public connector_;
DigitalIdLogic public logic_;
DigitalIdOracle public oracle_;
modifier checkLogic() {
if (logic_ != connector_.logic_()) {
logic_ = DigitalIdLogic(connector_.logic_());
}
_;
}
modifier checkOracle() {
if (oracle_ != connector_.oracle_()) {
oracle_ = DigitalIdOracle(connector_.oracle_());
}
_;
}
function DigitalIdInterface(address _connector) {
connector_ = DigitalIdConnector(_connector);
}
function linkEID(bytes _crt, bytes _sig)
external
checkLogic
payable {
logic_.linkEID.value(msg.value)(msg.sender, _crt, _sig);
}
function retryFailedCallback()
external
checkOracle
payable {
oracle_.retryCallback.value(msg.value)(msg.sender);
// add event resume
}
function retryFailedCallback(address _linked)
external
checkOracle
payable {
oracle_.retryCallback.value(msg.value)(_linked);
// add event resume
}
function requestOCSPCheck(address _user)
external
checkOracle
payable {
oracle_.requestPostOCSPCheck.value(msg.value)(_user, msg.sender);
}
function revokeOwnAddress()
external {
logic_.revocationRequest(msg.sender);
}
function getEIDCheckCost()
external constant
returns (uint) {
return DigitalIdCostEstimator(connector_.coster_()).expectedOracleCosts(false);
}
function getEIDCheckCostWithSHA1()
external constant
returns (uint) {
return DigitalIdCostEstimator(connector_.coster_()).expectedOracleCosts(true);
}
}
contract DigitalIdDatabase {
struct PublicKey {
bytes mod;
bytes exp;
}
struct Certificate {
// uint id;
string commonName;
PublicKey publicKey;
bytes crtSignature;
byte crtSigAlgorithm; // 05 = sha1, // 0b = sha256
uint40 serialNumber;
bytes20 parentId;
bool validated;
bool ocspRevoked;
uint ocspLastTimestamp;
uint ocspLastBlock;
uint txNonce;
bytes bodyHash;
}
struct Resident {
bytes32 certificateHash;
bytes usrSignature;
uint8 validityLevel;
bool userRevoked;
}
address public owner_;
mapping (bytes32 => Certificate) private certificate_;
mapping (address => Resident) private eResident_;
mapping (bytes20 => bytes) public parentCrts_;
DigitalIdConnector public connector_;
DigitalIdLogic public logic_;
DigitalIdOracle public oracle_;
modifier onlyOwner() { if (msg.sender != owner_) throw; _; }
modifier onlyLogic() { if (msg.sender != connector_.logic_()) throw; _; }
modifier onlyOracle() { if (msg.sender != connector_.oracle_()) throw; _; }
modifier onlyWalletOracle() { if (msg.sender != connector_.walletOracle_()) throw; _; }
modifier checkLogic() {
if (logic_ != connector_.logic_()) {
logic_ = DigitalIdLogic(connector_.logic_());
}
_;
}
modifier checkOracle() {
if (oracle_ != connector_.oracle_()) {
oracle_ = DigitalIdOracle(connector_.oracle_());
}
_;
}
function DigitalIdDatabase(address _connector) {
owner_ = msg.sender;
connector_ = DigitalIdConnector(_connector);
}
/* add these manually after the fact as owner
function whiteListParents()
private {
// using ones needed as specified by
// https://www.sk.ee/en/repository/certs/
// ESTEID-SK 2011
parentCrts_[0x7B6AF255505CB8D97A088741AEFAA22B3D5B5776] = hex'b3e97c6c661eabfda5dc35ede44a934c3aa990a005d4a73cdcaf8652686661ffb247222a65bcd8bab5b5bf94aeec02246c6fae4accc5913846ae95deba8206c33e06ba914f7b0be0171aeefe0d1397b2d8d43afe9596b1d95409cb9883a4c9ca566b18ccf847d03d9b83c446e4c3de81dff7c6ebd65ba77b3dcba58487053963d222425f184e41a7354c627506ce375046426f87544b204dfdb627aafa1b716c134eeb9cc36c90d0b70e3b8b48250a178907d2b54654af4176209d15a6631c4ca48f08c81b3aa7cb1c9129ee186c9e81f40066f797921603011ed644614faad15508406840180bab3935e35a2d53b2c038da69cb190644239197317b5a6e9e75';
// ESTEID-SK 2015
parentCrts_[0xB3AB88BC99D562A4852A08CDB41D723B83724751] = hex'd281fad4d0f16dd5bd93c9cb035a8668be01eefc9da1dd84c29fd24c1641df012d20908b764a44b12f295df16246ac0356c80619bbbe43df6dae56f92c8ef28bbac8911a2fe4d7ed05d48d3d2539ac08583d086f6594203b045a1dae44cbe05a2c91e62ea6104bd850bd0b02632c2cfb156f3455292b4a460fae22c9ca9d32e065fe75aaddf2ee669a70061d15165b66e2786bff54b447d4d1269a855066c6af838afc3c1e6d0e4f8e1752e3480250dc260bb7cf438bc81fec7e4c2936686faedcca00cf422ba555aa8b0cc6fefc6b7ae3cf02481778509e61fe9f5cbb06cf85a2bec6456e9876a4c8c42eeeac96d9415df006ddf1afe37b7dd555e2732cd1fde4f976c07ecc5b16d6c1d5fb538d3ebfaace00f1087d9c9aeaa864d7c822af9bba86f7780f1e7be5e924a250afed6a1ab9a18208ef02173b9ba714e31fd07f1c1162121536125ffac2954e191085b27d5f1b8a937735f30ca6c0bd66a430f43c8189aa5b2c31e8ae2782336a015b80448634351de22726d21413f029907949b519b59e058b1ea8f84c417f7b40504b5c92d5cb6482ca8033ec1ab5a80e37fbe11c89b37ec817359d0b36668abc724f4c2b46c2c4331e524414cfa55e406a7af4898e42bb30e3aa93cf49ad750acc49b9e45c2b8b6a7e5d3e6dbce09f4799aaa2622ea3e8a2dc6763645270d015eb015653049be7c76b6891ea59c0158674e941';
}
*/
function onlyOwnerModifier()
private
onlyOwner {
}
function onlyLogicModifier()
private
onlyLogic {
}
function checkIdOracleModifier()
private
checkOracle {
}
function onlyIdOracleModifier()
private
onlyOracle {
}
function onlyWalletOracleModifier()
private
onlyWalletOracle {
}
function addParent(bytes20 _id, bytes _modulus)
external {
onlyOwnerModifier();
parentCrts_[_id] = _modulus;
}
function removeParent(bytes20 _id)
external {
onlyOwnerModifier();
delete parentCrts_[_id];
}
// status: 0x01 = pass
// 0x02 = internal error; retryable
// 0x03 = sig verification fail
// 0x04 = ocsp revoked/unknown status
event linkingStatus(address indexed linked, uint level, byte status);
event addedEID(address indexed linked, string commonName);
function emitLinkEvent(address _linked, uint _level, byte _status) {
onlyIdOracleModifier();
linkingStatus(_linked, _level, _status);
}
event validatingCrtStatus(bytes32 indexed certificateId, uint level, byte status);
event addedCrt(bytes32 indexed certificateId, string commonName, uint40 indexed serial);
function emitValidatingEvent(bytes32 _crtId, uint _level, byte _status) {
onlyWalletOracleModifier();
validatingCrtStatus(_crtId, _level, _status);
}
function addEID(bytes32 _crtHash, address _address, string _commonName, bytes _usrSig)
external {
onlyLogicModifier();
eResident_[_address] = Resident(_crtHash, _usrSig, 1, false);
addedEID(_address, _commonName);
}
function addCrt(bytes32 _crtHash, bytes _bodyHash, string _commonName, bytes _mod, bytes _exp, bytes _crtSig, byte _crtSigAlgo, bytes20 _parentId, uint40 _serial) {
onlyLogicModifier();
Certificate memory crt = certificate_[_crtHash];
if (crt.validated == false) {
certificate_[_crtHash] = Certificate(_commonName, PublicKey(_mod, _exp), _crtSig, _crtSigAlgo, _serial, _parentId, false, false, 0, 0, 0, _bodyHash);
addedCrt(_crtHash, _commonName, _serial);
}
}
/*// has to be separated due to stack limit...
function addBodyHash(address _address, bytes _hash)
external
onlyLogic {
onlyLogicModifier();
bytes32 crtId = eResident_[_address].certificateHash;
if (certificate_[crtId].bodyHash.length == 0) {
certificate_[crtId].bodyHash = _hash;
}
}*/
function appendSHA1BodyHash(address _address, bytes _sha1)
external {
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
appendSHA1BodyHash(crtId, _sha1);
}
function appendSHA1BodyHash(bytes32 _crtId, bytes _sha1)
public {
if (msg.sender != connector_.walletOracle_() &&
msg.sender != connector_.oracle_()) {
throw;
}
// allow overwrite in case computation is invalid, as
// to not invalidate a cert permanently from db then
certificate_[_crtId].bodyHash = _sha1;
}
function setValidityEID(address _address, uint8 _level)
external {
onlyIdOracleModifier();
uint currentLevel = eResident_[_address].validityLevel;
if (_level < 5 && _level == currentLevel + 1) {
eResident_[_address].validityLevel = _level; //initial validation
if (_level == 2) {
bytes32 crtId = eResident_[_address].certificateHash;
certificate_[crtId].validated = true;
}
}
else if (_level == 4 && _level == currentLevel) {
return; // This is a successful ocsp check, no state changes
}
else {
throw;
}
}
function setCrtValidated(bytes32 _crtId)
external
returns (bool) {
onlyWalletOracleModifier();
certificate_[_crtId].validated = true;
}
function incrementCrtTxNonce(bytes32 _crtId, uint _txNonce)
external
returns (bool) {
onlyWalletOracleModifier();
if (_txNonce != certificate_[_crtId].txNonce)
return false;
certificate_[_crtId].txNonce++;
return true;
}
function ocspUpdateEID(address _address, bool _revoking)
external
returns (bool) {
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
return ocspUpdate(crtId, _revoking);
}
function ocspUpdateCrt(bytes32 _crtId, bool _revoking)
external
returns (bool) {
onlyWalletOracleModifier();
return ocspUpdate(_crtId, _revoking);
}
function ocspUpdate(bytes32 _crtId, bool _revoking)
private
returns (bool) {
certificate_[_crtId].ocspLastTimestamp = block.timestamp;
certificate_[_crtId].ocspLastBlock = block.number;
// DEBUG - Disable for production
certificate_[_crtId].ocspRevoked = _revoking;
/*
if (_revoking == true) {
revokeCrt(_crtId);
}
*/
return true;
}
// indicates certificate-wide revocation
function revokeCrt(bytes32 _crtId)
private {
certificate_[_crtId].ocspRevoked = true;
}
// revoke only for address
function selfRevokeEID(address _address)
external {
onlyLogicModifier();
eResident_[_address].userRevoked = true;
eResident_[_address].validityLevel = 10; // to indicate self revocation
}
// in case other contracts fail or get attacked, revocation is still possible
function selfDirectRevokeEID()
external {
if (!isValidatedEID(msg.sender))
throw;
eResident_[msg.sender].userRevoked = true;
eResident_[msg.sender].validityLevel = 10;
}
function eResident(address _address)
external constant
returns (string commonName, bytes mod, bytes exp, bytes crtSignature, bytes usrSignature, bytes bodyHash, bytes20 parentId, byte sigAlgo) {
Resident memory res = eResident_[_address];
(commonName, mod, exp, crtSignature, bodyHash, parentId, sigAlgo) = getCrtDetails(res.certificateHash);
usrSignature = res.usrSignature;
}
function eResidentValidity(address _address)
external constant
returns (uint8 validityLevel, bool isRevoked) {
Resident memory res = eResident_[_address];
validityLevel = res.validityLevel;
isRevoked = res.userRevoked || certificate_[res.certificateHash].ocspRevoked;
}
function getCrtDetails(bytes32 _crtId)
public constant
returns (string commonName, bytes mod, bytes exp, bytes crtSignature, bytes bodyHash, bytes20 parentId, byte sigAlgo) {
Certificate memory crt = certificate_[_crtId];
commonName = crt.commonName;
mod = crt.publicKey.mod;
exp = crt.publicKey.exp;
crtSignature = crt.crtSignature;
sigAlgo = crt.crtSigAlgorithm;
parentId = crt.parentId;
bodyHash = crt.bodyHash;
}
function getCrtStatus(bytes32 _crtId)
external constant
returns(bool valid, bool revoked, uint ocspLastTimestamp, uint ocspLastBlock) {
Certificate memory crt = certificate_[_crtId];
valid = crt.validated;
revoked = crt.ocspRevoked;
ocspLastTimestamp = crt.ocspLastTimestamp;
ocspLastBlock = crt.ocspLastBlock;
}
function isValidatedEID(address _address)
public constant
returns (bool valid) {
Resident memory res = eResident_[_address];
if (res.validityLevel == 4 && !res.userRevoked && !certificate_[res.certificateHash].ocspRevoked)
valid = true;
}
function getSerialCrt(bytes32 _crtId)
external constant
returns (uint40) {
return certificate_[_crtId].serialNumber;
}
function getCrtTxNonce(bytes32 _crtId)
external constant
returns (uint) {
return certificate_[_crtId].txNonce;
}
function getPublicKeyEID(address _address)
external constant
returns (bytes mod, bytes exp) {
bytes32 crtId = eResident_[_address].certificateHash;
mod = certificate_[crtId].publicKey.mod;
exp = certificate_[crtId].publicKey.exp;
}
function getParentEID(address _address)
external
returns (bytes20) {
bytes32 crtId = eResident_[_address].certificateHash;
return certificate_[crtId].parentId;
}
function pipeHashEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
oracle_.sendPipe(certificate_[crtId].bodyHash);
return true;
}
function pipeCommonNameEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
oracle_.sendPipe(bytes(certificate_[crtId].commonName));
return true;
}
function pipeCrtSigEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
oracle_.sendPipe(certificate_[crtId].crtSignature);
return true;
}
function pipeUsrSigEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
oracle_.sendPipe(eResident_[_address].usrSignature);
return true;
}
function pipeUsrModEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
oracle_.sendPipe(certificate_[crtId].publicKey.mod);
return true;
}
function pipeUsrExpEID(address _address)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
bytes32 crtId = eResident_[_address].certificateHash;
oracle_.sendPipe(certificate_[crtId].publicKey.exp);
return true;
}
function pipeParentMod(bytes20 _id)
external
returns (bool) {
checkIdOracleModifier();
onlyIdOracleModifier();
oracle_.sendPipe(parentCrts_[_id]);
return true;
}
function pipeSigOCSP(bytes _crt, address _requestingOracle)
external
checkLogic
returns (bool) {
onlyLogicModifier();
checkIdOracleModifier();
OraclesPipeAPI(_requestingOracle).sendPipe(_crt);
return true;
}
//||||||||||||||||||||||
function pipeToWalletOracle(bytes32 _crtId, uint _varId)
returns (bool) {
onlyWalletOracleModifier();
Certificate memory crt = certificate_[_crtId];
bytes memory pipe;
if (_varId == 1)
pipe = bytes(crt.commonName);
else if (_varId == 2)
pipe = crt.publicKey.mod;
else if (_varId == 3)
pipe = crt.publicKey.exp;
else if (_varId == 4)
pipe = crt.crtSignature;
else if (_varId == 5)
pipe = crt.bodyHash;
else if (_varId == 6)
pipe = parentCrts_[crt.parentId];
if (_varId >= 1 && _varId <= 6) {
WalletOracle(msg.sender).sendPipe(pipe);
return true;
}
}
}
contract DigitalIdLogic {
struct PublicKey {
bytes mod;
bytes exp;
}
// todo add last ocsp check timestamp
// todo add function to run post ocsp callback optional
struct Certificate {
// uint id;
string commonName;
PublicKey publicKey;
bytes signature;
byte sigAlgorithm; // 05 = sha1, // 0b = sha256
bytes20 parentId;
bytes bodyHash;
}
//JSON public json_;
DigitalIdConnector public connector_;
DigitalIdDatabase public database_;
DigitalIdOracle public oracle_;
modifier onlyInterface() { if (msg.sender != connector_.interface_()) throw; _; }
modifier onlyDatabase() { if (msg.sender != connector_.database_()) throw; _; }
modifier onlyOracles() { if (msg.sender != connector_.oracle_() && msg.sender != connector_.walletOracle_()) throw; _; }
modifier onlyWalletOracle() { if (msg.sender != connector_.walletOracle_()) throw; _; }
modifier checkOracle() {
if (oracle_ != connector_.oracle_()) {
oracle_ = DigitalIdOracle(connector_.oracle_());
}
_;
}
/*modifier checkCrtOracle() {
if (oracle_ != connector_.crtOracle_()) {
oracle_ = WalletOracle(connector_.crtOracle_());
}
_;
}*/
function DigitalIdLogic(address _connector) {
//OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
connector_ = DigitalIdConnector(_connector);
database_ = DigitalIdDatabase(connector_.database_());
}
function revocationRequest(address _linked) {
if (!database_.isValidatedEID(_linked))
throw;
database_.selfRevokeEID(_linked);
}
function extractCrt(bytes _crt)
internal returns (Certificate) {
// uint id;
bytes memory commonName;
bytes memory modulus;
bytes memory exponent;
bytes20 parentId;
byte sigAlgorithm; // 05 = sha1, 0b = sha256
bytes memory signature;
bytes memory hash;
(commonName, modulus, exponent, parentId) = extractNameKeyParent(_crt);
(signature, sigAlgorithm, hash) = extractSigAlgoHash(_crt);
return Certificate(string(commonName), PublicKey(modulus, exponent), signature, sigAlgorithm, parentId, hash);
}
/*function addEID(address _address, string _commonName, bytes _mod, bytes _exp,
bytes _signature, byte _sigAlgo, bytes20 _parentId, bytes _bodyHash)
*/
function linkEID(address _linked, bytes _crt, bytes _addressSig)
external
payable
onlyInterface
checkOracle {
// address can only have 1 EID ever
// should be secure enough, but could be avoided by initially providing
// malformed cert without parentEID, could throw if there's none, or
// throw if break is passed
if (database_.getParentEID(_linked) != 0 || _linked == address(0))
throw;
bytes32 crtHash = sha3(_crt);
Certificate memory thisCrt = extractCrt(_crt);
database_.addCrt(crtHash, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) :
thisCrt.bodyHash, thisCrt.commonName, thisCrt.publicKey.mod,
thisCrt.publicKey.exp, thisCrt.signature, thisCrt.sigAlgorithm,
thisCrt.parentId, parseSerialFromCN(thisCrt.commonName));
// last argument clears body for SHA-1, to not save 2kb to storage
database_.addEID(crtHash, _linked, thisCrt.commonName, _addressSig);
//database_.addBodyHash(_linked, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash);
oracle_.validateCrt.value(msg.value)(_linked, thisCrt.signature, thisCrt.bodyHash, thisCrt.sigAlgorithm, thisCrt.parentId);
}
function addCrtWallet(bytes _crt)
onlyWalletOracle
external {
bytes32 crtHash = sha3(_crt);
Certificate memory thisCrt = extractCrt(_crt);
database_.addCrt(crtHash, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) :
thisCrt.bodyHash, thisCrt.commonName, thisCrt.publicKey.mod,
thisCrt.publicKey.exp, thisCrt.signature, thisCrt.sigAlgorithm,
thisCrt.parentId, parseSerialFromCN(thisCrt.commonName));
/*WalletOracle(msg.sender).processNewCrt(crtHash, _signed, _addressType, _receiverSerial, _receiverAddress, _transferValue, thisCrt.bodyHash, thisCrt.sigAlgorithm);*/
WalletOracle(msg.sender).processNewCrt(crtHash, thisCrt.bodyHash, thisCrt.signature, thisCrt.sigAlgorithm);
// last argument clears body for SHA-1, to not save 2kb to storage
//database_.addBodyHash(_linked, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash);
//oracle_.validateCrt.value(msg.value)(_linked, thisCrt.signature, thisCrt.bodyHash, thisCrt.sigAlgorithm, thisCrt.parentId);
}
// assumes Serial will always be 11 last characters in the common name
function parseSerialFromCN(string _commonName)
private
constant returns (uint40) {
bytes memory converted = bytes(_commonName);
uint idIndex = converted.length - 11;
bytes memory parsed = new bytes(11);
for(uint i = 0; idIndex < converted.length; i++) {
parsed[i] = converted[idIndex];
idIndex++;
}
return uint40(oraclizeLib.parseInt(string(parsed)));
}
// helpers
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset)
private returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
assembly {
add(minLength, toOffset)
to
mstore
}
bytes memory newSized = new bytes(minLength);
newSized = to;
to = newSized;
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function extractNameKeyParent(bytes _crt)
private returns (bytes commonName, bytes modulus, bytes exponent, bytes20 parentId) {
bool skipFirst;
uint len;
for (uint i=30; i<_crt.length; i++) {
if (_crt[i] != 0x30)
continue;
if (commonName.length == 0) {
// check for auth message with i - 3
if (_crt[i+4] == 0x55 && _crt[i+5] == 0x04
&& _crt[i+6] == 0x03 && _crt[i+7] == 0x0C) {
// skip the first occurrence, which is name of parent cert
if (!skipFirst) {
skipFirst = true;
i += uint(_crt[i+8]) + 8 - 1; //skip this element
continue;
}
len = uint(_crt[i+8]);
i += 9;
commonName = new bytes(len);
commonName = copyBytes(_crt, i, len, commonName, 0);
i += len - 1;
continue;
}
}
else if (modulus.length == 0) {
if (_crt[i+4] == 0x02 && _crt[i+5] == 0x82 && _crt[i+6] == 0x01) {
i += 8;
while(_crt[i] == 0x00)
i++;
modulus = new bytes(0x20*8);
modulus = copyBytes(_crt, i, 0x20*8, modulus, 0);
i += 0x20*8 + 1;
// get exponent that follows
len = uint(_crt[i++]);
exponent = new bytes(len);
// mask based on indicated length
assembly {
let tmp := mload(add(_crt, add(i, 0x20)))
let trunc := exp(0x10,sub(0x40, mul(len, 2)))
div(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, trunc)
trunc
mul
tmp
and
add(exponent, 0x20)
mstore
}
continue;
}
}
else {
if (_crt[i+1] == 0x16 && _crt[i+2] == 0x80 && _crt[i+3] == 0x14) {
i += 4;
// parse for bytes20
assembly {
let tmp := mload(add(_crt, add(i, 0x20)))
and(tmp, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000)
=: parentId
}
break;
}
}
}
}
function extractSigAlgoHash(bytes _crt)
private returns (bytes signature, byte sigAlgorithm, bytes hash) {
// extract algo and sig + calc hash
for (uint i = 1; i<_crt.length; i++) {
if (_crt[i] != 0x30)
continue;
uint fromIndex = i;
uint size = uint(_crt[i+1]) - 0x80;
// COULD BE bug
//i += size;
// replaced with
i += 2;
uint seqOffset = 2;
uint len;
while (size > 0) {
len = (len * (0x10 ** 2)) + uint(_crt[i++]);
size--;
seqOffset++;
}
i += len;
sigAlgorithm = _crt[i+12];
hash = getBodyHash(_crt, fromIndex, len, sigAlgorithm, seqOffset);
// get sig itself
i += 17;
len = 0;
// search until occurrance of null byte in sig
while (_crt[i] != 0x00) {
len = (len * (0x10 ** 2)) + uint(_crt[i++]);
}
// discount null
len -= 1;
signature = new bytes(len);
signature = copyBytes(_crt, _crt.length - len, len, signature, 0);
break;
}
}
function getBodyHash(bytes _crt, uint _from, uint _len, byte _algo, uint _offset)
private returns (bytes) {
// assign sufficient size so sig is ignored
// CHANGED was + before but doesn't make sense to me
// was _len + _from
// coincidentally this was working only because the correct seqOffset
// matched with _from
bytes memory body = new bytes(_len + _offset);
// offset initial sequence
body = copyBytes(_crt, _from, body.length, body, 0);
if (_algo == 0x0b) {
bytes32 tmp = sha256(body);
bytes memory hash;
assembly {
mstore(hash, 0x20)
mstore(add(hash, 0x20), tmp)
}
return hash;
}
else if (_algo == 0x05) {
// return extracted body, so SHA-1 is done off-chain
return body;
}
}
function extractCrtOCSP(bytes _crt)
external
onlyOracles
returns (bool ocsp, bytes32 resHash) {
for (uint i = 0; i < _crt.length; i++) {
if (_crt[i] != 0x30)
continue;
if (_crt[i+1] != 0x09)
continue;
// match identifier
if (_crt[i+2] == 0x06 && _crt[i+3] == 0x05 && _crt[i+4] == 0x2B && _crt[i+5] == 0x0E && _crt[i+6] == 0x03 && _crt[i+7] == 0x02 && _crt[i+8] == 0x1A) {
uint offset = uint(_crt[i-1]);
i += offset;
if(_crt[i] == 0x80 && _crt[i+1] == 0x00)
ocsp = true;
uint lenSize = uint(_crt[35]) - 0x80;
i = 36;
uint seqOffset = 2;
uint len;
while (lenSize > 0) {
len = (len * (0x10 ** 2)) + uint(_crt[i++]);
seqOffset++;
lenSize--;
}
// get body hash of response
bytes memory body = new bytes(len + seqOffset);
// offset initial sequence
body = copyBytes(_crt, 34, len, body, 0);
resHash = sha256(body);
// get sig and pipe it to correct oracle
appendSigOCSP(_crt, 34 + len);
break;
}
}
}
function appendSigOCSP(bytes _crt, uint _offset)
private {
for (uint i = _offset; i < _crt.length; i++) {
if (_crt[i] != 0x30)
continue;
if (_crt[i+1] != 0x0D)
continue;
// match identifier
if (_crt[i+2] == 0x06 && _crt[i+3] == 0x09 && _crt[i+4] == 0x2A && _crt[i+5] == 0x86 && _crt[i+6] == 0x48 && _crt[i+7] == 0x86 && _crt[i+8] == 0xF7 && _crt[i+9] == 0x0D && _crt[i+10] == 0x01 && _crt[i+11] == 0x01 && _crt[i+12] == 0x0B) {
i += 20;
bytes memory signature = new bytes(256);
signature = copyBytes(_crt, i, 256, signature, 0);
// use msg.sender to pipe to correct oracle
database_.pipeSigOCSP(signature, msg.sender);
break;
}
}
}
}
contract DigitalIdCostEstimator {
uint24[5] public execCost_ = [
2000000, // sha1 computation
2000000, // rsa cert sig validation
2000000, // rsa addr sig validation (should be same as above)
2000000, // ocsp query
1800000 // rsa ocsp response validation
];
function DigitalIdCostEstimator() {
/*oraclizeLib.oraclize_setProof(0x00);
oraclizeLib.oraclize_query("URL", "");*/
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function getOAR() constant returns (address) {
return oraclizeLib.getOAR();
}
function expectedOracleCosts(bool _sha1)
public constant returns (uint) {
//uint estimatedQueryCost = getOracleGasCost("URL", queryGasCost);
/*uint crtComputationCost = getOracleGasCost("computation", 1800000);
uint sha1ComputationCost = _sha1 ? getOracleGasCost("computation", 1500000) : 0;
uint ocspQueryCost = getOracleGasCost("nested", 4000000);
*/
uint totalCost;
uint oracleStep = _sha1 ? 0 : 1;
// load storage array into memory for efficiency
uint24[5] memory costs = execCost_;
string memory ds;
for (; oracleStep < costs.length; oracleStep++) {
ds = oracleStep == 3 ? "nested" : "computation";
totalCost += getOracleGasCost(ds, costs[oracleStep]);
}
return totalCost;
}
function expectedOCSPCosts()
public constant
returns (uint) {
uint totalCost;
uint24[5] memory costs = execCost_;
totalCost += getRequestCost(3);
totalCost += getRequestCost(4);
return totalCost;
}
// General helpers
function getOracleGasCost(string _type, uint _gasNeeded)
public constant returns (uint) {
if (_gasNeeded <= 200000)
return (oraclizeLib.oraclize_getPrice(_type, 200001) / 200001) * 200000;
else
return oraclizeLib.oraclize_getPrice(_type, _gasNeeded);
}
function getRequestCost(uint _action)
public constant returns (uint) {
string memory ds = _action == 3 ? "nested" : "computation";
return getOracleGasCost(ds, execCost_[_action]);
}
}
contract DigitalIdOracle is usingFixedToDynamicLibrary {
// TODO Add suicides to the 2 logics
enum cbAction { ComputeHash, ComputeCertSig, ComputeAddrSig, QueryOCSP, ComputeOCSPSig/*, ComputeMsgSig*/ }
struct Callback {
address sender;
cbAction action;
bool retry;
}
struct OCSPRevocation {
bool pass;
bytes32 hash;
}
mapping (bytes32 => Callback) private cbTracker_;
mapping (address => bytes32) private cbRetry_;
//mapping (address => bytes32) private revokingHash_;
mapping (bytes32 => OCSPRevocation) private cbRevoking_;
//mapping (bytes32 => OCSPRevocation) private
//JSON public json_;
DigitalIdConnector public connector_;
DigitalIdDatabase public database_;
DigitalIdLogic public logic_;
DigitalIdCostEstimator public coster_;
// work-around for sending dynamic types between contracts
bytes private pipe_;
uint24[5] public execCost_ = [
2000000, // sha1 computation
2000000, // rsa cert sig validation
2000000, // rsa addr sig validation (should be same as above)
2000000, // ocsp query
1800000 // rsa ocsp response validation
];
modifier onlyLogic() { if (msg.sender != connector_.logic_()) throw; _; }
modifier onlyInterface() { if (msg.sender != connector_.interface_()) throw; _; }
modifier onlyDatabase() { if (msg.sender != connector_.database_()) throw; _; }
function DigitalIdOracle(address _connector) {
connector_ = DigitalIdConnector(_connector);
// Database must be pre-deployed already
database_ = DigitalIdDatabase(connector_.database_());
coster_ = DigitalIdCostEstimator(connector_.coster_());
//oraclize_setProof(proofType_NONE);
//oraclize_query('URL', '');
}
function validateCrt(address _linked, bytes _signature, bytes _bodyHash, byte _sigAlgo, bytes20 _parentId)
external
onlyLogic
payable {
//bytes20 parent = ;
//bytes memory parentMod = database_.getHashEID(address(0));
bytes32 callback;
cbAction action;
if (_sigAlgo == 0x0b) { // sha-256
bytes memory parentExp = hex'010001';
if (database_.pipeParentMod(_parentId))
bytes memory parentMod = pipe_;
else
throw;
action = cbAction.ComputeCertSig;
callback = computeRSA(_signature, parentExp, parentMod, execCost_[uint(action)]);
}
else if(_sigAlgo == 0x05) { //sha-1
callback = computeSHA1(_bodyHash);
action = cbAction.ComputeHash;
}
else {
throw;
}
trackCallback(_linked, action, callback);
uint cost = coster_.expectedOracleCosts(cbTracker_[callback].action == cbAction.ComputeHash);
if (msg.value < cost)
throw;
if (!_linked.send(msg.value - cost))
throw;
}
function trackCallback(address _usr, cbAction _action, bytes32 _cb)
private {
cbTracker_[_cb] = Callback(_usr, _action, false);
}
function computeRSA(bytes _base, bytes _exp, bytes _mod, uint _cost)
private
returns (bytes32 callback) {
/*string[3] memory params = [oraclizeLib.b2s(_base), oraclizeLib.b2s(_exp), oraclizeLib.b2s(_mod)];
string[] memory arr;
arr[0] = oraclizeLib.b2s(_base);
arr[1] = oraclizeLib.b2s(_exp);
arr[2] = oraclizeLib.b2s(_mod);*/
//string[] storage arr = ["Qmd3Vdr5AqFCLDqWhx8fcpQKM6FoUMMieR4cGEyNmL44hJ", base, exp, mod];
return oraclizeLib.oraclize_query("computation", ["binary(QmfFdnXLRzhiks7BRbJ3UZmc99WVYXwHissHeJSB1sxHw6).unhexlify()",
oraclizeLib.b2s(_base), oraclizeLib.b2s(_exp), oraclizeLib.b2s(_mod)].toDynamic(), _cost);
}
function computeSHA1(bytes _body)
private
returns (bytes32 callback) {
return oraclizeLib.oraclize_query("computation", ["binary(QmeTKU7RYZ4NpxHPKAP4oa6znp7hre1SozBtGa9qvD1L7w).unhexlify()",
oraclizeLib.b2s(_body)].toDynamic(), execCost_[0]);
}
function requestPostOCSPCheck(address _user, address _requester)
external
onlyInterface
payable {
uint cost = coster_.expectedOCSPCosts();
if (msg.value < cost)
throw;
if (database_.pipeCommonNameEID(_user))
string memory cn = string(pipe_);
else
throw;
trackCallback(_user, cbAction.QueryOCSP, queryOCSP(cn));
if (!_requester.send(msg.value - cost))
throw;
}
function queryOCSP(string _cn)
private
returns (bytes32 callback) {
return oraclizeLib.oraclize_query("nested",
oraclizeLib.strConcat("[URL] http://esteid.oraclize.it/ocsp/_sign?otype=cert&key=${[decrypt] BG+04c4ksqrXd+YyV/AtAXkpfg017wRxBkxcxtKtVHml9VXuEo++koFXVWqKfiAo7TU2KamWspeCzsMSRddOggszdWaSJ5bQUrxw6tBZ9JdfDuvLQiEjJX8EOGd7BGw2LTD04Umk4zU1Fc2iyQzAx2G9ztZXrkF8+1EYoyvDTvlIGT2/PT5lgWWjauYs5iwtrg==}&cn=", _cn), execCost_[3]);
}
function verifySigOCSP(bytes _sig)
private
returns (bytes32 callback) {
bytes memory ocspResponderMod = hex'8a1bc6ca1315ae045e1e5b8a967d736ba82f084fe69524449968c91692fd965bee1146683c5232a5803c839bb555f824796e600eadb98c03aae05c977831886bea499f6874a3659cd9a7a9a551bf7a67c69bf8c0f238dec8caf01fc7c026ba9543b73d5f6c52c0911c87f3f677c09f319b79605ea0a8bb4fbc6d5bfa7ea8b41640e708c815f27f8a7241314bea1d2cf7f8f2dfc4edbf4f75b293f73c33d1c832a4de96aca230646059e8625353ac2fd6ab9afddd42b1ecd709babc76b17e97d607d6001697a8f5a62a84f0b156dff3a3635007abf1c994b486c3ab5cbed2c514e83896aab27be56dfd1eacf3c5b511d4bdba23618825f9fce5cf426de9026837';
return computeRSA(_sig, hex'010001', ocspResponderMod, execCost_[uint(cbAction.ComputeOCSPSig)]);
}
function sendPipe(bytes _pipe)
external
onlyDatabase {
pipe_ = _pipe;
}
// adds retry flag, allowing query to be re-attempted in case of service failure
function failedCallback(bytes32 _cb, address _sender)
private {
cbTracker_[_cb].retry = true;
cbRetry_[_sender] = _cb;
}
function retryCallback(address _linked)
external
onlyInterface
payable {
bytes32 cb = cbRetry_[_linked];
if (cb == 0)
throw;
Callback memory cbObj = cbTracker_[cb];
uint cost = coster_.getRequestCost(uint(cbObj.action));
// ensure sufficient amount was paid to pay for redoing the Callback
// IMPORTANT / DANGER check here for potential refund exploits
if (msg.value < cost)
throw;
requestOracleQuery(cb, cbObj, true);
delete cbRetry_[_linked];
// IMPORTANT / DANGER check here for potential refund exploits
if(!_linked.send(msg.value - cost))
throw;
}
function requestOracleQuery(bytes32 _cb, Callback _cbObj, bool _isRetry)
private {
requestOracleQuery(_cb, _cbObj, _isRetry, OCSPRevocation(false, 0));
}
function requestOracleQuery(bytes32 _cb, Callback _cbObj, bool _isRetry, OCSPRevocation _ocsp)
private {
uint nextAction = uint(_cbObj.action);
nextAction = _isRetry ? nextAction : nextAction + 1;
bytes memory sig;
if (nextAction == uint(cbAction.ComputeCertSig)) {
if (database_.pipeCrtSigEID(_cbObj.sender))
sig = pipe_;
else
throw;
if (database_.pipeParentMod(database_.getParentEID(_cbObj.sender)))
bytes memory parentMod = pipe_;
else
throw;
trackCallback(_cbObj.sender, cbAction.ComputeCertSig, computeRSA(sig, hex'010001', parentMod, execCost_[nextAction]));
}
else if (nextAction == uint(cbAction.ComputeAddrSig)) {
if (database_.pipeUsrSigEID(_cbObj.sender))
sig = pipe_;
else
throw;
if (database_.pipeUsrModEID(_cbObj.sender))
bytes memory mod = pipe_;
else
throw;
if (database_.pipeUsrExpEID(_cbObj.sender))
bytes memory exp = pipe_;
else
throw;
trackCallback(_cbObj.sender, cbAction.ComputeAddrSig, computeRSA(sig, exp, mod, execCost_[nextAction]));
}
else if (nextAction == uint(cbAction.QueryOCSP)) {
if (database_.pipeCommonNameEID(_cbObj.sender))
string memory cn = string(pipe_);
else
throw;
trackCallback(_cbObj.sender, cbAction.QueryOCSP, queryOCSP(cn));
}
else if (nextAction == uint(cbAction.ComputeOCSPSig)) {
// extracted sig already in pipe
sig = pipe_;
bytes32 cb = verifySigOCSP(sig);
//if (_ocsp.hash != 0)
cbRevoking_[cb] = _ocsp;
trackCallback(_cbObj.sender, cbAction.ComputeOCSPSig, cb);
}
// get storage refund
delete cbTracker_[_cb].sender;
delete cbTracker_[_cb].action;
if (_isRetry)
delete cbTracker_[_cb].retry;
}
function __callback(bytes32 _cb, string _result) {
if (msg.sender!= oraclizeLib.oraclize_cbAddress()) throw;
Callback memory cbObj = cbTracker_[_cb];
if(sha3(_result) == sha3("") || bytes(_result).length == 0) {
failedCallback(_cb, cbObj.sender);
database_.emitLinkEvent(cbObj.sender, 0, 0x02);
return;
}
// if retrieved hash is empty, result must be sha1
if (cbObj.action == cbAction.ComputeHash) {
bytes memory sha1 = bytes(_result);
if (sha1.length == 20) {
database_.appendSHA1BodyHash(cbObj.sender, sha1);
}
else {
database_.emitLinkEvent(cbObj.sender, 1, 0x03);
return;
}
// SHA-1 computed and added, begin cert RSA validation
requestOracleQuery(_cb, cbObj, false);
database_.emitLinkEvent(cbObj.sender, 1, 0x01);
return;
}
// runs for initial OCSP callback
if (cbObj.action == cbAction.QueryOCSP) {
bool ocspPass;
bytes32 ocspHash;
if (logic_ != connector_.logic_()) {
logic_ = DigitalIdLogic(connector_.logic_());
}
// sends extracted sig to pipe, for later use in requestOracleQuery
(ocspPass, ocspHash) = logic_.extractCrtOCSP(bytes(_result));
//bytes memory ocspSig = pipe_;
// check if user's cert passed ocsp
/*if (!ocspPass)
revoking_[cbObj.sender] = true;
else if(revoking_[cbObj.sender] == true)
delete revoking_[cbObj.sender];
*/
//database_.appendOCSPHash(cbObj.sender, ocspHash);
requestOracleQuery(_cb, cbObj, false, OCSPRevocation(ocspPass, ocspHash));
return;
}
bytes memory result = bytes(_result);
bytes memory hash;
// throw here so Oraclize is discouraged from providing false results
// TODO: To be decided, potentially useless as funds will be in this contract anyways
// also ends up not providing feedback to user
/*if (result[0] != 0x01)
throw;
*/
if (cbObj.action == cbAction.ComputeCertSig) {
if (database_.pipeHashEID(cbObj.sender))
hash = pipe_;
else
return; //potentially add retry here? although it shouldn't occur, and if it does, it's not retryable anyways
bytes memory resultHash = new bytes(hash.length);
resultHash = copyBytes(result, result.length - hash.length, hash.length, resultHash, 0);
if (sha3(hash) == sha3(resultHash)) {
database_.setValidityEID(cbObj.sender, 2);
// initiate address signature validation
requestOracleQuery(_cb, cbObj, false);
database_.emitLinkEvent(cbObj.sender, 2, 0x01);
return;
// do ocsp
}
else {
database_.emitLinkEvent(cbObj.sender, 2, 0x03);
return;
}
}
else if (cbObj.action == cbAction.ComputeAddrSig) {
bytes memory addressHash = new bytes(32);
addressHash = copyBytes(result, result.length - 32, 32, addressHash, 0);
if (sha3(sha256(cbObj.sender)) == sha3(addressHash)) {
database_.setValidityEID(cbObj.sender, 3);
// initiate OCSP revocation check
requestOracleQuery(_cb, cbObj, false);
database_.emitLinkEvent(cbObj.sender, 3, 0x01);
return;
}
else {
database_.emitLinkEvent(cbObj.sender, 3, 0x03);
return;
}
}
else if (cbObj.action == cbAction.ComputeOCSPSig) {
OCSPRevocation memory ocsp = cbRevoking_[_cb];
bytes memory resultOCSPHash = new bytes(32);
resultOCSPHash = copyBytes(result, result.length - 32, 32, resultOCSPHash, 0);
if (sha3(ocsp.hash) == sha3(resultOCSPHash)) {
if (ocsp.pass == false) {
// could be revoked wantonly with a malicious certificate, should track callback too
// not any longer, revocation is tied to specific cert used, not last
database_.ocspUpdateEID(cbObj.sender, true);
database_.emitLinkEvent(cbObj.sender, 4, 0x04);
return;
}
else {
// EID fully validated
database_.ocspUpdateEID(cbObj.sender, false);
database_.setValidityEID(cbObj.sender, 4);
database_.emitLinkEvent(cbObj.sender, 4, 0x01);
return;
}
}
else {
database_.emitLinkEvent(cbObj.sender, 4, 0x03);
return;
}
}
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset)
private returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
assembly {
add(minLength, toOffset)
to
mstore
}
bytes memory newSized = new bytes(minLength);
newSized = to;
to = newSized;
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
}
contract WalletOracle is usingFixedToDynamicLibrary {
// to receive oracle funding during testing
function () payable {
}
enum cbAction { ComputeHash, ComputeCertSig, QueryOCSP, ComputeOCSPSig, ComputeSigning }
enum pipeId { nil, commonName, mod, exp, crtSignature, bodyHash, parentMod }
struct Callback {
bytes32 crtId;
cbAction action;
bytes32 transferId;
}
struct OCSPRevocation {
bool pass;
bytes32 hash;
}
struct Transfer {
bytes signature;
address token;
bool executed;
bool transferred;
bool addressType; // true if type of receiver is address, false if eid
uint40 senderSerial;
uint40 receiverSerial;
address receiverAddress;
uint value;
string message;
uint nonce;
}
/*struct TempTransfer {
bytes signed;
address token;
bool addressType;
uint40 receiverSerial;
address receiverAddress;
uint value;
string message;
uint nonce;
}*/
Transfer private tempTransfer_;
mapping (bytes32 => Transfer) private transfer_;
mapping (bytes32 => Callback) private cbTracker_;
//mapping (address => bytes32) private revokingHash_;
mapping (bytes32 => OCSPRevocation) private cbRevoking_;
//mapping (bytes32 => OCSPRevocation) private
//JSON public json_;
DigitalIdConnector public connector_;
DigitalIdDatabase public database_;
WalletContainer public walletContainer_;
// work-around for sending dynamic types between contracts
bytes private pipe_;
/*
uint24[5] public execCost_ = [
2000000, // sha1 computation
1000000, // rsa cert sig validation
1100000,
1800000,
1000000 // rsa msg sig validation (should be same as above)
];*/
function WalletOracle(address _connector, address _wallet) {
connector_ = DigitalIdConnector(_connector);
// Database must be pre-deployed already
database_ = DigitalIdDatabase(connector_.database_());
walletContainer_ = WalletContainer(_wallet);
// oraclize_setProof(proofType_NONE);
}
function processNewCrt(bytes32 _crtId, bytes _bodyHash, bytes _crtSig, byte _sigAlgo)
external {
if (msg.sender != connector_.logic_()) throw;
//bytes20 parent = ;
Transfer memory trf = tempTransfer_;
uint40 senderSerial = database_.getSerialCrt(_crtId);
bytes32 transferId = sha3(_crtId, trf.signature, trf.addressType, senderSerial, trf.receiverSerial, trf.receiverAddress, trf.value, trf.message, trf.nonce); // transfer struct with exec and transf bools omitted
transfer_[transferId] = Transfer(trf.signature, trf.token, false, false, trf.addressType, senderSerial, trf.receiverSerial, trf.receiverAddress, trf.value, trf.message, trf.nonce);
//bytes memory parentMod = database_.getHashEID(address(0));
bytes32 callback;
cbAction action;
oraclizeLib.useCoupon('free');
if (_sigAlgo == 0x0b) { // sha-256
bytes memory parentExp = hex'010001';
if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.parentMod)))
throw;
bytes memory parentMod = pipe_;
action = cbAction.ComputeCertSig;
callback = idOracleLib.computeRSA(_crtSig, parentExp, parentMod, 2000000);
}
else if(_sigAlgo == 0x05) { //sha-1
callback = idOracleLib.computeSHA1(_bodyHash);
action = cbAction.ComputeHash;
}
else {
throw;
}
Callback memory cbObj = Callback(_crtId, action, transferId);
trackCallback(cbObj, action, callback);
// get refund from temp var
delete tempTransfer_;
//return transferId;
}
function extractNewCrtThenVerifySig(bytes _crt, bytes _signed, address _token, bool _addressType, uint40 _receiverSerial, address _receiverAddress, uint _transferValue, string _message, uint _nonce)
external
{
if (msg.sender != address(walletContainer_)) throw;
// save to storage for later re-use
tempTransfer_ = Transfer(_signed, _token, false, false, _addressType, 0, _receiverSerial, _receiverAddress, _transferValue, _message, _nonce);
// addCrtWallet will be routed to addNewCrt locally
DigitalIdLogic(connector_.logic_()).addCrtWallet(_crt);
}
function requestSigVerify(bytes32 _crtId, bytes _signed, address _token, bool _addressType, uint40 _senderSerial, uint40 _receiverSerial, address _receiverAddress, uint _transferValue, string _message, uint _nonce)
external {
if (msg.sender != address(walletContainer_)) throw;
requestSigVerify(_crtId, Transfer(_signed, _token, false, false, _addressType, _senderSerial, _receiverSerial, _receiverAddress, _transferValue, _message, _nonce));
}
// ~400k deployment gas :(
function requestSigVerify(bytes32 _crtId, Transfer _trf)
private {
bytes32 transferId = sha3(_crtId, _trf.signature, _trf.token, _trf.addressType, _trf.senderSerial, _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce);
transfer_[transferId] = _trf;
// stays in effect, there should be some reset
oraclizeLib.useCoupon('free');
// pipe vars needed from database
if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.mod)))
throw;
bytes memory mod = pipe_;
if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.exp)))
throw;
bytes memory exp = pipe_;
bytes32 cbRSA = idOracleLib.computeRSA(_trf.signature, exp, mod, 2500000);
Callback memory cbObj = Callback(_crtId, cbAction.ComputeSigning, transferId);
trackCallback(cbObj, cbAction.ComputeSigning, cbRSA);
}
function trackCallback(Callback _prevCbObj, cbAction _action, bytes32 _cb)
private {
cbTracker_[_cb] = Callback(_prevCbObj.crtId, _action, _prevCbObj.transferId);
}
function sendPipe(bytes _pipe)
external {
if (msg.sender != address(database_))
throw;
pipe_ = _pipe;
}
function requestOracleQuery(Callback _cbObj)
private {
requestOracleQuery(_cbObj, OCSPRevocation(false, 0));
}
function requestOracleQuery(Callback _cbObj, OCSPRevocation _ocsp)
private {
uint nextAction = uint(_cbObj.action);
nextAction = nextAction + 1;
bytes memory sig;
if (nextAction == uint(cbAction.ComputeCertSig)) {
if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.crtSignature)))
throw;
sig = pipe_;
if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.parentMod)))
throw;
bytes memory parentMod = pipe_;
trackCallback(_cbObj, cbAction.ComputeCertSig, idOracleLib.computeRSA(sig, hex'010001', parentMod, 1000000));
}
else if (nextAction == uint(cbAction.QueryOCSP)) {
if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.commonName)))
throw;
string memory cn = string(pipe_);
trackCallback(_cbObj, cbAction.QueryOCSP, idOracleLib.queryOCSP(cn));
}
else if (nextAction == uint(cbAction.ComputeOCSPSig)) {
// verify the provided signature with known valid ocsp cert
// extracted sig already in pipe
sig = pipe_;
bytes32 cb = idOracleLib.verifySigOCSP(sig);
//if (_ocsp.hash != 0)
cbRevoking_[cb] = _ocsp;
trackCallback(_cbObj, cbAction.ComputeOCSPSig, cb);
}
else if (nextAction == uint(cbAction.ComputeSigning)) {
// should do address to hash translation
// needs to be handled somehow :/, accessing wallet?
sig = transfer_[_cbObj.transferId].signature;
if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.mod)))
throw;
bytes memory mod = pipe_;
if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.exp)))
throw;
bytes memory exp = pipe_;
trackCallback(_cbObj, cbAction.ComputeSigning, idOracleLib.computeRSA(sig, exp, mod, 1000000));
}
// get storage refund
/*delete cbTracker_[_cb].crtId;
delete cbTracker_[_cb].action;*/
}
function __callback(bytes32 _cb, string _result) {
if (msg.sender != oraclizeLib.oraclize_cbAddress()) throw;
Callback memory cbObj = cbTracker_[_cb];
if(sha3(_result) == sha3("") || bytes(_result).length == 0) {
//failedCallback(_cb, cbObj.crtId);
database_.emitValidatingEvent(cbObj.crtId, 0, 0x02);
return;
}
// if retrieved hash is empty, result must be sha1
if (cbObj.action == cbAction.ComputeHash) {
bytes memory sha1 = bytes(_result);
if (sha1.length == 20) {
database_.appendSHA1BodyHash(cbObj.crtId, sha1);
}
else {
database_.emitValidatingEvent(cbObj.crtId, 1, 0x03);
return;
}
// SHA-1 computed and added, begin cert RSA validation
requestOracleQuery(cbObj);
database_.emitValidatingEvent(cbObj.crtId, 1, 0x01);
return;
}
// runs for initial OCSP callback
if (cbObj.action == cbAction.QueryOCSP) {
bool ocspPass;
bytes32 ocspHash;
DigitalIdLogic logic = DigitalIdLogic(connector_.logic_());
// sends extracted sig to pipe, for later use in requestOracleQuery
(ocspPass, ocspHash) = logic.extractCrtOCSP(bytes(_result));
//bytes memory ocspSig = pipe_;
// check if user's cert passed ocsp
//database_.appendOCSPHash(cbObj.sender, ocspHash);
requestOracleQuery(cbObj, OCSPRevocation(ocspPass, ocspHash));
return;
}
bytes memory result = bytes(_result);
// throw here so Oraclize is discouraged from providing false results
// TODO: To be decided, potentially useless as funds will be in this contract anyways
// also ends up not providing feedback to user
if (cbObj.action == cbAction.ComputeCertSig) {
bytes memory expectHash;
if (!database_.pipeToWalletOracle(cbObj.crtId, uint(pipeId.bodyHash)))
throw;
expectHash = pipe_;
// expectHash length is dependent upon sigAlgo, hence just base it off the state's expectHash
bytes memory resultHash = new bytes(expectHash.length);
resultHash = copyBytes(result, result.length - expectHash.length, expectHash.length, resultHash, 0);
if (sha3(expectHash) == sha3(resultHash)) {
database_.setCrtValidated(cbObj.crtId);
// initiate address signature validation
requestOracleQuery(cbObj);
database_.emitValidatingEvent(cbObj.crtId, 2, 0x01);
return;
}
else {
database_.emitValidatingEvent(cbObj.crtId, 2, 0x03);
return;
}
}
else if (cbObj.action == cbAction.ComputeOCSPSig) {
OCSPRevocation memory ocsp = cbRevoking_[_cb];
bytes memory resultOCSPHash = new bytes(32);
resultOCSPHash = copyBytes(result, result.length - 32, 32, resultOCSPHash, 0);
if (sha3(ocsp.hash) == sha3(resultOCSPHash)) {
if (ocsp.pass == false) {
// could be revoked wantonly with a malicious certificate, should track callback too
// not any longer, revocation is tied to specific cert used, not last
database_.ocspUpdateCrt(cbObj.crtId, true);
database_.emitValidatingEvent(cbObj.crtId, 3, 0x04);
return;
}
else {
// Crt passed OCSP check
database_.ocspUpdateCrt(cbObj.crtId, false);
requestOracleQuery(cbObj);
database_.emitValidatingEvent(cbObj.crtId, 3, 0x01);
return;
}
}
else {
database_.emitValidatingEvent(cbObj.crtId, 3, 0x03);
return;
}
}
else if (cbObj.action == cbAction.ComputeSigning) {
// should likely be last step, after ocsp checks complete
bytes memory signedHash = new bytes(32);
signedHash = copyBytes(result, result.length - 32, 32, signedHash, 0);
Transfer memory tfr = transfer_[cbObj.transferId];
if (sha3(
tfr.addressType ?
sha256(tfr.receiverAddress, tfr.token, tfr.value, tfr.message, tfr.nonce) :
sha256(tfr.receiverSerial, tfr.token, tfr.value, tfr.message, tfr.nonce)
)
== sha3(signedHash)
)
{
// call wallet here and execute transfer;
// ensure nonce is current
if (database_.incrementCrtTxNonce(cbObj.crtId, tfr.nonce)) {
walletContainer_.executeDelegatedTransfer(tfr.senderSerial, tfr.addressType, tfr.receiverSerial, tfr.receiverAddress, tfr.token, tfr.value, tfr.message);
database_.emitValidatingEvent(cbObj.crtId, 4, 0x01);
} else {
database_.emitValidatingEvent(cbObj.crtId, 4, 0x04);
}
return;
}
else {
database_.emitValidatingEvent(cbObj.crtId, 4, 0x03);
return;
}
}
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset)
private returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
assembly {
add(minLength, toOffset)
to
mstore
}
bytes memory newSized = new bytes(minLength);
newSized = to;
to = newSized;
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
}
// math.sol -- mixin for inline numerical wizardry
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
contract DSMath {
function assert(bool assertion) internal {
if (!assertion) throw;
}
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint public decimals;
string public name;
}
// handle ocsp revocation on poi-side
contract WalletContainer is DSMath {
struct Balance {
uint eth;
mapping(address => uint) token;
}
struct Transfer {
bytes signed;
address token;
bool addressType;
uint40 receiverSerial;
address receiverAddress;
uint value;
string message;
uint nonce;
}
Transfer transfer_;
mapping(uint40 => Balance) public balances_;
event LOG_receivedTransfer(uint40 indexed receiverSerial, uint40 senderSerial, address senderAddress, address indexed token, uint amount, string note, uint time);
event LOG_sentTransfer(uint40 indexed senderSerial, uint40 receiverSerial, address receiverAddress, address indexed token, uint amount, string note, uint time);
event LOG_balanceUpdate(uint40 indexed serial, address indexed token, uint amount, uint time);
DigitalIdConnector public connector_;
DigitalIdDatabase public database_;
WalletOracle public walletOracle_;
uint public birthBlock_;
modifier checkWalletOracle() {
if (walletOracle_ != connector_.walletOracle_()) {
walletOracle_ = WalletOracle(connector_.walletOracle_());
}
_;
}
// assumes all EID serials are and will be 11 digits
modifier serialCheck(uint40 _serial) {
if (_serial > 99999999999 || _serial < 10000000000)
throw;
_;
}
// connect to oracle here and db
function WalletContainer(address _connector) {
connector_ = DigitalIdConnector(_connector);
database_ = DigitalIdDatabase(connector_.database_());
birthBlock_ = block.number;
}
function getBalance(uint40 _serial)
public
constant
returns (uint) {
return getBalance(_serial, 0);
}
function getBalance(uint40 _serial, address _token)
public
constant
returns (uint) {
if (_token == 0)
return balances_[_serial].eth;
else
return balances_[_serial].token[_token];
}
function sendEtherToEID(uint40 _serial)
payable
external
returns (bool success) {
success = sendEtherToEID(_serial, '');
}
function sendEtherToEID(uint40 _serial, string _msg)
payable
serialCheck(_serial)
public
returns (bool success) {
balances_[_serial].eth = add(msg.value, balances_[_serial].eth);
LOG_receivedTransfer(_serial, 0, msg.sender, 0, msg.value, _msg, now);
success = true;
LOG_balanceUpdate(_serial, 0, balances_[_serial].eth, now);
}
function sendTokensToEID(uint40 _serial, address _token, uint _amount)
external
returns (bool success) {
// may be reserved for ether down the line?
success = sendTokensToEID(_serial, _token, _amount, '');
//balances_[_serial] = add()
}
function sendTokensToEID(uint40 _serial, address _token, uint _amount, string _msg)
serialCheck(_serial)
public
returns (bool success) {
// may be reserved for ether down the line?
if (_token == 0)
throw;
if (!Token(_token).transferFrom(msg.sender, this, _amount))
throw;
balances_[_serial].token[_token] = add(_amount, balances_[_serial].token[_token]);
LOG_receivedTransfer(_serial, 0, msg.sender, _token, _amount, _msg, now);
success = true;
LOG_balanceUpdate(_serial, _token, balances_[_serial].token[_token], now);
}
function transferEtherToAddress(bytes _crt, bytes _signed, address _signedReceiverAddress, uint _signedValue, string _signedMessage, uint _signedNonce)
external {
Transfer memory trf = Transfer(_signed, 0, true, 0, _signedReceiverAddress, _signedValue, _signedMessage, _signedNonce);
requestTransferToOracle(_crt, trf);
}
function transferTokenToAddress(bytes _crt, bytes _signed, address _signedToken, address _signedReceiverAddress, uint _signedValue, string _signedMessage, uint _signedNonce)
external {
Transfer memory trf = Transfer(_signed, _signedToken, true, 0, _signedReceiverAddress, _signedValue, _signedMessage, _signedNonce);
requestTransferToOracle(_crt, trf);
}
function transferEtherToSerial(bytes _crt, bytes _signed, uint40 _signedReceiverSerial, uint _signedValue, string _signedMessage, uint _signedNonce)
serialCheck(_signedReceiverSerial)
external {
Transfer memory trf = Transfer(_signed, 0, false, _signedReceiverSerial, 0, _signedValue, _signedMessage, _signedNonce);
requestTransferToOracle(_crt, trf);
}
function transferTokenToSerial(bytes _crt, bytes _signed, address _signedToken, uint40 _signedReceiverSerial, uint _signedValue, string _signedMessage, uint _signedNonce)
serialCheck(_signedReceiverSerial)
external {
Transfer memory trf = Transfer(_signed, _signedToken, false, _signedReceiverSerial, 0, _signedValue, _signedMessage, _signedNonce);
requestTransferToOracle(_crt, trf);
}
function requestTransferToOracle(bytes _crt, Transfer _trf)
private {
// send cert and sig to be verified
// check if crt is already in database
bytes32 crtId = sha3(_crt);
// maybe check at end post-increment?!
// CURRENTLY ALLOWS ONLY FOR ONE TX AT A TIME AND NOT QEUEING SEVERAL
if (database_.getCrtTxNonce(crtId) != _trf.nonce)
throw;
bool valid;
bool revoked;
uint ocspLastTimestamp;
uint ocspLastBlock;
(valid, revoked, ocspLastTimestamp, ocspLastBlock) = database_.getCrtStatus(crtId);
if(revoked) {
//DEBUG don't throw if revoked
//throw;
onlyTrfSigValidation(_crt, crtId, _trf);
}
else if(valid && ocspLastTimestamp > 0) {
onlyTrfSigValidation(_crt, crtId, _trf);
}
else {
fullCrtValidation(_crt, _trf);
}
}
function onlyTrfSigValidation(bytes _crt, bytes32 _crtId, Transfer _trf)
checkWalletOracle
private {
// check here if there's even sufficient balance, so not to waste computing resources
if (!sufficientBalance(database_.getSerialCrt(_crtId), _trf.token, _trf.value))
throw;
// TODO
// periodic ocsp check or ocsp check above certain amounts!?
walletOracle_.requestSigVerify(_crtId, _trf.signed, _trf.token, _trf.addressType, database_.getSerialCrt(_crtId), _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce);
}
function fullCrtValidation(bytes _crt, Transfer _trf)
checkWalletOracle
private {
// schedule for trf sig validation
walletOracle_.extractNewCrtThenVerifySig(_crt, _trf.signed, _trf.token, _trf.addressType, _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce);
}
function sufficientBalance(uint40 _serial, address _token, uint _value)
private
constant
returns (bool) {
if (_token == 0)
return balances_[_serial].eth >= _value;
else
return balances_[_serial].token[_token] >= _value;
}
function executeDelegatedTransfer(uint40 _senderSerial, bool _addressType, uint40 _receiverSerial, address _receiverAddress, address _token, uint _value, string _msg)
external
returns (bool transferred) {
// only allow current walletOracle to execute the transfer
if(msg.sender != connector_.walletOracle_())
throw;
if(_addressType) {
if(_token == 0) {
return executeAddressTransferETH(_senderSerial, _receiverAddress, _value, _msg);
}
else {
return executeAddressTransferToken(_senderSerial, _receiverAddress, _token, _value, _msg);
}
}
else {
if(_token == 0) {
return executeSerialTransferETH(_senderSerial, _receiverSerial, _value, _msg);
}
else {
return executeSerialTransferToken(_senderSerial, _receiverSerial, _token, _value, _msg);
}
}
}
function executeAddressTransferETH(uint40 _senderSerial, address _receiverAddress, uint _value, string _msg)
private
returns (bool transferred) {
if (balances_[_senderSerial].eth >= _value) {
// underflow check
balances_[_senderSerial].eth = sub(balances_[_senderSerial].eth, _value);
if(!_receiverAddress.send(_value)) {
return false;
}
// emit event here
LOG_sentTransfer(_senderSerial, 0, _receiverAddress, 0, _value, _msg, now);
LOG_balanceUpdate(_senderSerial, 0, balances_[_senderSerial].eth, now);
return true;
}
else {
// emit event here
return false;
}
}
function executeAddressTransferToken(uint40 _senderSerial, address _receiverAddress, address _token, uint _value, string _msg)
private
returns (bool transferred) {
if (balances_[_senderSerial].token[_token] >= _value) {
// underflow check
balances_[_senderSerial].token[_token] = sub(balances_[_senderSerial].token[_token], _value);
if(!Token(_token).transfer(_receiverAddress, _value)) {
return false;
}
// emit event here
LOG_sentTransfer(_senderSerial, 0, _receiverAddress, _token, _value, _msg, now);
LOG_balanceUpdate(_senderSerial, _token, balances_[_senderSerial].token[_token], now);
return true;
}
else {
// emit event here
return false;
}
}
function getHashForTransfer(uint40 _serialReceiver, address _token, uint _value, string _msg, uint _nonce)
public
constant
returns (bytes32 hash) {
// address 0 is considered ether tokens
hash = sha256(_serialReceiver, _token, _value, _msg, _nonce);
}
function getHashForTransfer(address _addressReceiver, address _token, uint _value, string _msg, uint _nonce)
public
constant
returns (bytes32 hash) {
hash = sha256(_addressReceiver, _token, _value, _msg, _nonce);
}
function executeSerialTransferETH(uint40 _senderSerial, uint40 _receiverSerial, uint _value, string _msg)
private
returns (bool transferred) {
if (balances_[_senderSerial].eth >= _value) {
balances_[_senderSerial].eth = sub(balances_[_senderSerial].eth, _value); // add underflow/overflow checks
balances_[_receiverSerial].eth = add(balances_[_receiverSerial].eth, _value);
// emit event here
LOG_sentTransfer(_senderSerial, _receiverSerial, 0, 0, _value, _msg, now);
LOG_balanceUpdate(_senderSerial, 0, balances_[_senderSerial].eth, now);
LOG_receivedTransfer(_receiverSerial, _senderSerial, 0, 0, _value, _msg, now);
LOG_balanceUpdate(_receiverSerial, 0, balances_[_receiverSerial].eth, now);
return true;
}
else {
// emit event here
return false;
}
}
function executeSerialTransferToken(uint40 _senderSerial, uint40 _receiverSerial, address _token, uint _value, string _msg)
private
returns (bool transferred) {
if (balances_[_senderSerial].token[_token] >= _value) {
// remove balance from sender
balances_[_senderSerial].token[_token] = sub(balances_[_senderSerial].token[_token], _value);
// add balance towards receiver
balances_[_receiverSerial].token[_token] = add(balances_[_receiverSerial].token[_token], _value);
// emit event here
LOG_sentTransfer(_senderSerial, _receiverSerial, 0, _token, _value, _msg, now);
LOG_balanceUpdate(_senderSerial, _token, balances_[_senderSerial].token[_token], now);
LOG_receivedTransfer(_receiverSerial, _senderSerial, 0, _token, _value, _msg, now);
LOG_balanceUpdate(_receiverSerial, _token, balances_[_receiverSerial].token[_token], now);
return true;
}
else {
// emit event here
return false;
}
}
}
|
in case other contracts fail or get attacked, revocation is still possible
|
function selfDirectRevokeEID()
external {
if (!isValidatedEID(msg.sender))
throw;
eResident_[msg.sender].userRevoked = true;
eResident_[msg.sender].validityLevel = 10;
}
| 5,533,991
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC1155.sol";
// EulerBeats are generative visual & audio art pieces. The recipe and instructions to re-create the visualization and music reside on Ethereum blockchain.
//
// To recreate your art, you will need to retrieve the script
//
// STEPS TO RETRIEVE THE SCRIPTS:
// - The artwork re-generation script is written in JavaScript, split into pieces, and stored on chain.
// - Query the contract for the scriptCount - this is the number of pieces of the re-genereation script. You will need all of them.
// - Run the getScriptAtIndex method in the EulerBeats smart contract starting with parameter 0, this is will return a transaction hash
// - The "Input Data" field of this transaction contains the first segment of the script. Convert this into UTF-8 format
// - Repeat these last two steps, incrementing the parameter in the getScriptAtIndex method until the number of script segments matches the scrtipCount
contract EulerBeats is Ownable, ERC1155 {
using SafeMath for uint256;
/***********************************|
| Variables and Events |
|__________________________________*/
// For Minting and Burning, locks the prices
bool private _enabled = false;
// For metadata (scripts), when locked, cannot be changed
bool private _locked = false;
// Number of script sections stored
uint256 public scriptCount = 0;
// The scripts that can be used to render the NFT (audio and visual)
mapping (uint256 => string) scripts;
// The 40 bit is flag to distinguish prints - 1 for print
uint256 constant SEED_MASK = uint40(~0);
uint256 constant PRINTS_FLAG_BIT = 1 << 39;
// Supply restriction on prints
uint256 constant MAX_PRINT_SUPPLY = 120;
// Supply restriction on seeds/original NFTs
uint256 constant MAX_SEEDS_SUPPLY = 27;
// Total supply of prints and seeds/original NFTs
mapping(uint256 => uint256) public totalSupply;
// Total number of seeds/original NFTs minted
uint256 public originalsMinted = 0;
// Owner of the seed/original NFT
mapping(uint256 => address payable) public seedToOwner;
// Cost of minting an original/seed
uint256 public mintPrice = 0.271 ether;
// Funds reserved for burns
uint256 public reserve = 0;
// For bonding curve
uint256 constant K = 1 ether;
uint256 constant B = 50;
uint256 constant C = 26;
uint256 constant D = 8;
uint256 constant SIG_DIGITS = 3;
/**
* @dev Emitted when an original NFT with a new seed is minted
*/
event MintOriginal(address indexed to, uint256 seed, uint256 indexed originalsMinted);
/**
* @dev Emitted when an print is minted
*/
event PrintMinted(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 pricePaid,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 royaltyPaid,
uint256 reserve,
address indexed royaltyRecipient
);
/**
* @dev Emitted when an print is burned
*/
event PrintBurned(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 priceReceived,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 reserve
);
constructor(string memory _uri) ERC1155("EulerBeats", "eBEATS", _uri) {}
/***********************************|
| Modifiers |
|__________________________________*/
modifier onlyWhenEnabled() {
require(_enabled, "Contract is disabled");
_;
}
modifier onlyWhenDisabled() {
require(!_enabled, "Contract is enabled");
_;
}
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
/***********************************|
| User Interactions |
|__________________________________*/
/**
* @dev Function to mint tokens. Msg.value must be sufficient
*/
function mint() public payable onlyWhenEnabled returns (uint256) {
uint256 newOriginalsSupply = originalsMinted.add(1);
require(
newOriginalsSupply <= MAX_SEEDS_SUPPLY,
"Max supply reached"
);
require(msg.value == mintPrice, "Insufficient payment");
// The generated seed == the original nft token id.
// Both terms are used throughout and refer to the same thing.
uint256 seed = _generateSeed(newOriginalsSupply);
// Increment the supply per original nft (max: 1)
totalSupply[seed]++;
assert(totalSupply[seed] == 1);
// Update total originals minted
originalsMinted = newOriginalsSupply;
_mint(msg.sender, seed, 1, "");
emit MintOriginal(msg.sender, seed, newOriginalsSupply);
return seed;
}
/**
* @dev Function to mint prints from an existing seed. Msg.value must be sufficient.
* @param seed The NFT id to mint print of
*/
function mintPrint(uint256 seed)
public
payable
onlyWhenEnabled
returns (uint256)
{
require(seedToOwner[seed] != address(0), "Seed does not exist");
uint256 tokenId = getPrintTokenIdFromSeed(seed);
uint256 oldSupply = totalSupply[tokenId];
// Get price to mint the next print
uint256 printPrice = getPrintPrice(oldSupply + 1);
require(msg.value >= printPrice, "Insufficient funds");
uint256 newSupply = totalSupply[tokenId].add(1);
totalSupply[tokenId] = newSupply;
// Update reserve - reserveCut == Price to burn next token
uint256 reserveCut = getBurnPrice(newSupply);
reserve = reserve.add(reserveCut);
// Calculate fees - seedOwner gets 80% of fee (printPrice - reserveCut)
uint256 seedOwnerRoyalty = _getSeedOwnerCut(printPrice.sub(reserveCut));
// Mint token
_mint(msg.sender, tokenId, 1, "");
// Disburse royalties
address seedOwner = seedToOwner[seed];
(bool success, ) = seedOwner.call{value: seedOwnerRoyalty}("");
require(success, "Payment failed");
// Remaining 20% kept for contract/Treum
// If buyer sent extra ETH as padding in case another purchase was made they are refunded
_refundSender(printPrice);
emit PrintMinted(msg.sender, tokenId, seed, printPrice, getPrintPrice(newSupply.add(1)), reserveCut, newSupply, seedOwnerRoyalty, reserve, seedOwner);
return tokenId;
}
/**
* @dev Function to burn a print
* @param seed The seed for the print to burn.
* @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage.
* Set to 1 to allow burn to go through no matter what the price is.
*/
function burnPrint(uint256 seed, uint256 minimumSupply) public onlyWhenEnabled {
require(seedToOwner[seed] != address(0), "Seed does not exist");
uint256 tokenId = getPrintTokenIdFromSeed(seed);
uint256 oldSupply = totalSupply[tokenId];
require(oldSupply >= minimumSupply, 'Min supply not met');
uint256 burnPrice = getBurnPrice(oldSupply);
uint256 newSupply = totalSupply[tokenId].sub(1);
totalSupply[tokenId] = newSupply;
// Update reserve
reserve = reserve.sub(burnPrice);
_burn(msg.sender, tokenId, 1);
// Disburse funds
(bool success, ) = msg.sender.call{value: burnPrice}("");
require(success, "Burn payment failed");
emit PrintBurned(msg.sender, tokenId, seed, burnPrice, getPrintPrice(oldSupply), getBurnPrice(newSupply), newSupply, reserve);
}
/***********************************|
| Public Getters - Pricing |
|__________________________________*/
/**
* @dev Function to get print price
* @param printNumber the print number of the print Ex. if there are 2 existing prints, and you want to get the
* next print price, then this should be 3 as you are getting the price to mint the 3rd print
*/
function getPrintPrice(uint256 printNumber) public pure returns (uint256 price) {
require(printNumber <= MAX_PRINT_SUPPLY, "Maximum supply exceeded");
uint256 decimals = 10 ** SIG_DIGITS;
if (printNumber < B) {
price = (10 ** ( B.sub(printNumber) )).mul(decimals).div(11 ** ( B.sub(printNumber)));
} else if (printNumber == B) {
price = decimals; // price = decimals * (A ^ 0)
} else {
price = (11 ** ( printNumber.sub(B) )).mul(decimals).div(10 ** ( printNumber.sub(B) ));
}
price = price.add(C.mul(printNumber));
price = price.sub(D);
price = price.mul(1 ether).div(decimals);
}
/**
* @dev Function to get funds received when burned
* @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds
* receive on burn the supply should be 2
*/
function getBurnPrice(uint256 supply) public pure returns (uint256 price) {
uint256 printPrice = getPrintPrice(supply);
price = printPrice * 90 / 100; // 90 % of print price
}
/***********************************|
| Public Getters - Seed + Prints |
|__________________________________*/
/**
* @dev Get the number of prints minted for the corresponding seed
* @param seed The seed/original NFT token id
*/
function seedToPrintsSupply(uint256 seed)
public
view
returns (uint256)
{
uint256 tokenId = getPrintTokenIdFromSeed(seed);
return totalSupply[tokenId];
}
/**
* @dev The token id for the prints contains the seed/original NFT id
* @param seed The seed/original NFT token id
*/
function getPrintTokenIdFromSeed(uint256 seed) public pure returns (uint256) {
return seed | PRINTS_FLAG_BIT;
}
/***********************************|
| Public Getters - Metadata |
|__________________________________*/
function getScriptAtIndex(uint256 index) public view returns (string memory) {
require(index < scriptCount, "Index out of bounds");
return scripts[index];
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* @return URI string
*/
function uri(uint256 _id) public override view returns (string memory) {
return string(abi.encodePacked(_uri, _uint2str(_id), ".json"));
}
/***********************************|
|Internal Functions - Generate Seed |
|__________________________________*/
function _generateSeed(uint256 uniqueValue) internal view returns (uint256) {
bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number - 1), msg.sender, uniqueValue));
// gridLength 0-5
uint8 gridLength = uint8(hash[0]) % 6;
// horizontalLever 0-58
uint8 horizontalLever = uint8(hash[1]) % 59;
// diagonalLever 0-10
uint8 diagonalLever = uint8(hash[2]) % 11;
// palette 4 0-11
uint8 palette = uint8(hash[3]) % 12;
// innerShape 0-3 with rarity
uint8 innerShape = _getRareTrait(uint8(hash[4]) % 9);
return uint256(uint40(gridLength) << 32 | uint40(horizontalLever) << 24 | uint40(diagonalLever) << 16 | uint40(palette) << 8 | uint40(innerShape));
}
function _getRareTrait(uint8 value) internal pure returns (uint8) {
// 70% circle
// 10% square;
// 10% squareCircle;
// 10% squareDiamond;
if (value > 2) {
return 3;
} else {
return value;
}
}
/***********************************|
| Internal Functions - Prints |
|__________________________________*/
function _getSeedOwnerCut(uint256 fee) internal pure returns (uint256) {
return fee.mul(8).div(10);
}
function _refundSender(uint256 printPrice) internal {
if (msg.value.sub(printPrice) > 0) {
(bool success, ) =
msg.sender.call{value: msg.value.sub(printPrice)}("");
require(success, "Refund failed");
}
}
/***********************************|
| Admin |
|__________________________________*/
/**
* @dev Set mint price for seed/original NFT
* @param _mintPrice The cost of an original
*/
function setPrice(uint256 _mintPrice) public onlyOwner onlyWhenDisabled {
mintPrice = _mintPrice;
}
function addScript(string memory _script) public onlyOwner onlyUnlocked {
scripts[scriptCount] = _script;
scriptCount = scriptCount.add(1);
}
function updateScript(string memory _script, uint256 index) public onlyOwner onlyUnlocked {
require(index < scriptCount, "Index out of bounds");
scripts[index] = _script;
}
function resetScriptCount() public onlyOwner onlyUnlocked {
scriptCount = 0;
}
/**
* @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds.
*/
function withdraw() public onlyOwner {
uint256 withdrawableFunds = address(this).balance.sub(reserve);
msg.sender.transfer(withdrawableFunds);
}
/**
* @dev Function to enable/disable token minting
* @param enabled The flag to turn minting on or off
*/
function setEnabled(bool enabled) public onlyOwner {
_enabled = enabled;
}
/**
* @dev Function to lock/unlock the on-chain metadata
* @param locked The flag turn locked on
*/
function setLocked(bool locked) public onlyOwner onlyUnlocked {
_locked = locked;
}
/**
* @dev Function to update the base _uri for all tokens
* @param newuri The base uri string
*/
function setURI(string memory newuri) public onlyOwner {
_setURI(newuri);
}
/***********************************|
| Hooks |
|__________________________________*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
// If token is original, keep track of owner so can send them fees
if (ids[i] & PRINTS_FLAG_BIT != PRINTS_FLAG_BIT) {
uint256 seed = ids[i];
seedToOwner[seed] = payable(to);
}
}
}
/***********************************|
| Utility Internal Functions |
|__________________________________*/
/**
* @notice Convert uint256 to string
* @param _i Unsigned integer to convert to string
*/
function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 ii = _i;
uint256 len;
// Get number of bytes
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
// Get each individual ASCII
while (ii != 0) {
bstr[k--] = byte(uint8(48 + ii % 10));
ii /= 10;
}
// Convert to string
return string(bstr);
}
}
// 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 "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
*
* @dev CLONE OF THE BASIC ERC1155 CONTRACT FROM OPEN ZEPPELIN
* Only changes made are changing the uri related variable and getter
* to be internal and virtual.
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// contract name
string public name;
// contract symbol
string public symbol;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string internal _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory name_, string memory symbol_, string memory uri_) {
name = name_;
symbol = symbol_;
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @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 ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// 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 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);
}
|
If token is original, keep track of owner so can send them fees
|
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
if (ids[i] & PRINTS_FLAG_BIT != PRINTS_FLAG_BIT) {
uint256 seed = ids[i];
seedToOwner[seed] = payable(to);
}
}
}
|__________________________________*/
| 1,085,654
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../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.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
/// @title DumenoToken
/// @author Dumeno Team
contract DumenoToken is ERC20 {
using SafeMath for uint256;
uint256 internal constant BASE_UNITS = 1000000000000000000;
uint256 internal constant INITIAL_MINT = 100000000 * BASE_UNITS;
/// @notice The treasury address that controls the initial supply.
address public treasury;
/// @notice This is true if the initial supply is minted.
bool public isInitialSupplyMinted;
/// @notice MintInitialSupply is emmited when the initial supply is emitted to the treasury.
event MintInitialSupply();
/// @dev Can only be called by treasury.
modifier onlyTreasury() {
require(msg.sender == treasury, "DumenoToken::onlyTreasury: MUST_TREASURY");
_;
}
constructor() ERC20("Dumeno", "DMN") {
treasury = msg.sender;
}
/// @notice Mint the initial supply (10 % of the Dumeno tokens) to the Treasury.
/// @param _mints The addresses that receive intial mints.
/// @param _amounts The amount each mint receives.
/// @param _cnt The number of mint and amount parameters (must match).
function mintInitialSupply(
address[] calldata _mints,
uint256[] calldata _amounts,
uint256 _cnt
) external onlyTreasury {
// Ensure that the mint can only be executed once.
require(isInitialSupplyMinted == false, "DumenoToken::mintInitialSupply: ALREADY_EXECUTED");
// Ensure the integrity of the mints.
require(_mints.length == _cnt, "DumenoToken::mintIntialSupply: BAD_MINT_CNT");
require(_amounts.length == _cnt, "DumenoToken::mintIntialSupply: BAD_AMOUNTS_CNT");
uint256 sum = 0;
// Issue tokens to every mint.
for (uint256 i = 0; i < _cnt; i++) {
_mint(_mints[i], _amounts[i]);
sum = sum.add(_amounts[i]);
}
// If there are any remaining, issue to the Treasury.
if (sum < INITIAL_MINT) {
_mint(treasury, INITIAL_MINT.sub(sum));
}
isInitialSupplyMinted = true;
emit MintInitialSupply();
}
}
|
Mint the initial supply (10 % of the Dumeno tokens) to the Treasury. _mints The addresses that receive intial mints. _amounts The amount each mint receives. _cnt The number of mint and amount parameters (must match). Ensure that the mint can only be executed once. Ensure the integrity of the mints. Issue tokens to every mint. If there are any remaining, issue to the Treasury.
|
function mintInitialSupply(
address[] calldata _mints,
uint256[] calldata _amounts,
uint256 _cnt
) external onlyTreasury {
require(isInitialSupplyMinted == false, "DumenoToken::mintInitialSupply: ALREADY_EXECUTED");
require(_mints.length == _cnt, "DumenoToken::mintIntialSupply: BAD_MINT_CNT");
require(_amounts.length == _cnt, "DumenoToken::mintIntialSupply: BAD_AMOUNTS_CNT");
uint256 sum = 0;
for (uint256 i = 0; i < _cnt; i++) {
_mint(_mints[i], _amounts[i]);
sum = sum.add(_amounts[i]);
}
if (sum < INITIAL_MINT) {
_mint(treasury, INITIAL_MINT.sub(sum));
}
isInitialSupplyMinted = true;
emit MintInitialSupply();
}
| 6,033,194
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {IOracle} from "./interfaces/IOracle.sol";
import "./interfaces/IButtonToken.sol";
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title The ButtonToken ERC20 wrapper.
*
* @dev The ButtonToken is a rebasing wrapper for fixed balance ERC-20 tokens.
*
* Users deposit the "underlying" (wrapped) tokens and are
* minted button (wrapper) tokens with elastic balances
* which change up or down when the value of the underlying token changes.
*
* For example: Manny “wraps” 1 Ether when the price of Ether is $1800.
* Manny receives 1800 ButtonEther tokens in return.
* The overall value of their ButtonEther is the same as their original Ether,
* however each unit is now priced at exactly $1. The next day,
* the price of Ether changes to $1900. The ButtonEther system detects
* this price change, and rebases such that Manny’s balance is
* now 1900 ButtonEther tokens, still priced at $1 each.
*
* The ButtonToken math is almost identical to Ampleforth's μFragments.
*
* For AMPL, internal balances are represented using `gons` and
* -> internal account balance `_gonBalances[account]`
* -> internal supply scalar `gonsPerFragment = TOTAL_GONS / _totalSupply`
* -> public balance `_gonBalances[account] * gonsPerFragment`
* -> public total supply `_totalSupply`
*
* In our case internal balances are stored as 'bits'.
* -> underlying token unit price `p_u = price / 10 ^ (PRICE_DECIMALS)`
* -> total underlying tokens `_totalUnderlying`
* -> internal account balance `_accountBits[account]`
* -> internal supply scalar `_bitsPerToken`
` = TOTAL_BITS / (MAX_UNDERLYING*p_u)`
* ` = BITS_PER_UNDERLYING*(10^PRICE_DECIMALS)/price`
* ` = PRICE_BITS / price`
* -> user's underlying balance `(_accountBits[account] / BITS_PER_UNDERLYING`
* -> public balance `_accountBits[account] * _bitsPerToken`
* -> public total supply `_totalUnderlying * p_u`
*
*
*/
contract ButtonToken is IButtonToken, Initializable, OwnableUpgradeable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// We make the following guarantees:
// - If address 'A' transfers x button tokens to address 'B'.
// A's resulting external balance will be decreased by "precisely" x button tokens,
// and B's external balance will be "precisely" increased by x button tokens.
// - If address 'A' deposits y underlying tokens,
// A's resulting underlying balance will increase by "precisely" y.
// - If address 'A' withdraws y underlying tokens,
// A's resulting underlying balance will decrease by "precisely" y.
//
using SafeERC20 for IERC20;
//--------------------------------------------------------------------------
// Constants
/// @dev The price has a 8 decimal point precision.
uint256 public constant PRICE_DECIMALS = 8;
/// @dev Math constants.
uint256 private constant MAX_UINT256 = type(uint256).max;
/// @dev The maximum units of the underlying token that can be deposited into this contract
/// ie) for a underlying token with 18 decimals, MAX_UNDERLYING is 1B tokens.
uint256 public constant MAX_UNDERLYING = 1_000_000_000e18;
/// @dev TOTAL_BITS is a multiple of MAX_UNDERLYING so that {BITS_PER_UNDERLYING} is an integer.
/// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_BITS = MAX_UINT256 - (MAX_UINT256 % MAX_UNDERLYING);
/// @dev Number of BITS per unit of deposit.
uint256 private constant BITS_PER_UNDERLYING = TOTAL_BITS / MAX_UNDERLYING;
/// @dev Number of BITS per unit of deposit * (1 USD).
uint256 private constant PRICE_BITS = BITS_PER_UNDERLYING * (10**PRICE_DECIMALS);
/// @dev TRUE_MAX_PRICE = maximum integer < (sqrt(4*PRICE_BITS + 1) - 1) / 2
/// Setting MAX_PRICE to the closest two power which is just under TRUE_MAX_PRICE.
uint256 public constant MAX_PRICE = (2**96 - 1); // (2^96) - 1
//--------------------------------------------------------------------------
// Attributes
/// @inheritdoc IButtonWrapper
address public override underlying;
/// @inheritdoc IButtonToken
address public override oracle;
/// @inheritdoc IButtonToken
uint256 public override lastPrice;
/// @dev Rebase counter
uint256 _epoch;
/// @inheritdoc IERC20Metadata
string public override name;
/// @inheritdoc IERC20Metadata
string public override symbol;
/// @dev internal balance, bits issued per account
mapping(address => uint256) private _accountBits;
/// @dev ERC20 allowances
mapping(address => mapping(address => uint256)) private _allowances;
//--------------------------------------------------------------------------
// Modifiers
modifier validRecipient(address to) {
require(to != address(0x0), "ButtonToken: recipient zero address");
require(to != address(this), "ButtonToken: recipient token address");
_;
}
modifier onAfterRebase() {
uint256 price;
bool valid;
(price, valid) = _queryPrice();
if (valid) {
_rebase(price);
}
_;
}
//--------------------------------------------------------------------------
/// @param underlying_ The underlying ERC20 token address.
/// @param name_ The ERC20 name.
/// @param symbol_ The ERC20 symbol.
/// @param oracle_ The oracle which provides the underlying token price.
function initialize(
address underlying_,
string memory name_,
string memory symbol_,
address oracle_
) public override initializer {
require(underlying_ != address(0), "ButtonToken: invalid underlying reference");
// Initializing ownership to `msg.sender`
__Ownable_init();
underlying = underlying_;
name = name_;
symbol = symbol_;
// MAX_UNDERLYING worth bits are 'pre-mined' to `address(0x)`
// at the time of construction.
//
// During mint, bits are transferred from `address(0x)`
// and during burn, bits are transferred back to `address(0x)`.
//
// No more than MAX_UNDERLYING can be deposited into the ButtonToken contract.
_accountBits[address(0)] = TOTAL_BITS;
updateOracle(oracle_);
}
//--------------------------------------------------------------------------
// Owner only actions
/// @inheritdoc IButtonToken
function updateOracle(address oracle_) public override onlyOwner {
uint256 price;
bool valid;
oracle = oracle_;
(price, valid) = _queryPrice();
require(valid, "ButtonToken: unable to fetch data from oracle");
emit OracleUpdated(oracle);
_rebase(price);
}
//--------------------------------------------------------------------------
// ERC20 description attributes
/// @inheritdoc IERC20Metadata
function decimals() external view override returns (uint8) {
return IERC20Metadata(underlying).decimals();
}
//--------------------------------------------------------------------------
// ERC-20 token view methods
/// @inheritdoc IERC20
function totalSupply() external view override returns (uint256) {
uint256 price;
(price, ) = _queryPrice();
return _bitsToAmount(_activeBits(), price);
}
/// @inheritdoc IERC20
function balanceOf(address account) external view override returns (uint256) {
if (account == address(0)) {
return 0;
}
uint256 price;
(price, ) = _queryPrice();
return _bitsToAmount(_accountBits[account], price);
}
/// @inheritdoc IRebasingERC20
function scaledTotalSupply() external view override returns (uint256) {
return _bitsToUAmount(_activeBits());
}
/// @inheritdoc IRebasingERC20
function scaledBalanceOf(address account) external view override returns (uint256) {
if (account == address(0)) {
return 0;
}
return _bitsToUAmount(_accountBits[account]);
}
/// @inheritdoc IERC20
function allowance(address owner_, address spender) external view override returns (uint256) {
return _allowances[owner_][spender];
}
//--------------------------------------------------------------------------
// ButtonWrapper view methods
/// @inheritdoc IButtonWrapper
function totalUnderlying() external view override returns (uint256) {
return _bitsToUAmount(_activeBits());
}
/// @inheritdoc IButtonWrapper
function balanceOfUnderlying(address who) external view override returns (uint256) {
if (who == address(0)) {
return 0;
}
return _bitsToUAmount(_accountBits[who]);
}
/// @inheritdoc IButtonWrapper
function underlyingToWrapper(uint256 uAmount) external view override returns (uint256) {
uint256 price;
(price, ) = _queryPrice();
return _bitsToAmount(_uAmountToBits(uAmount), price);
}
/// @inheritdoc IButtonWrapper
function wrapperToUnderlying(uint256 amount) external view override returns (uint256) {
uint256 price;
(price, ) = _queryPrice();
return _bitsToUAmount(_amountToBits(amount, price));
}
//--------------------------------------------------------------------------
// ERC-20 write methods
/// @inheritdoc IERC20
function transfer(address to, uint256 amount)
external
override
validRecipient(to)
onAfterRebase
returns (bool)
{
_transfer(_msgSender(), to, _amountToBits(amount, lastPrice), amount);
return true;
}
/// @inheritdoc IRebasingERC20
function transferAll(address to)
external
override
validRecipient(to)
onAfterRebase
returns (bool)
{
uint256 bits = _accountBits[_msgSender()];
_transfer(_msgSender(), to, bits, _bitsToAmount(bits, lastPrice));
return true;
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) external override validRecipient(to) onAfterRebase returns (bool) {
if (_allowances[from][_msgSender()] != type(uint256).max) {
_allowances[from][_msgSender()] -= amount;
emit Approval(from, _msgSender(), _allowances[from][_msgSender()]);
}
_transfer(from, to, _amountToBits(amount, lastPrice), amount);
return true;
}
/// @inheritdoc IRebasingERC20
function transferAllFrom(address from, address to)
external
override
validRecipient(to)
onAfterRebase
returns (bool)
{
uint256 bits = _accountBits[from];
uint256 amount = _bitsToAmount(bits, lastPrice);
if (_allowances[from][_msgSender()] != type(uint256).max) {
_allowances[from][_msgSender()] -= amount;
emit Approval(from, _msgSender(), _allowances[from][_msgSender()]);
}
_transfer(from, to, bits, amount);
return true;
}
/// @inheritdoc IERC20
function approve(address spender, uint256 amount) external override returns (bool) {
_allowances[_msgSender()][spender] = amount;
emit Approval(_msgSender(), spender, amount);
return true;
}
// @inheritdoc IERC20
function increaseAllowance(address spender, uint256 addedAmount) external returns (bool) {
_allowances[_msgSender()][spender] += addedAmount;
emit Approval(_msgSender(), spender, _allowances[_msgSender()][spender]);
return true;
}
// @inheritdoc IERC20
function decreaseAllowance(address spender, uint256 subtractedAmount) external returns (bool) {
if (subtractedAmount >= _allowances[_msgSender()][spender]) {
delete _allowances[_msgSender()][spender];
} else {
_allowances[_msgSender()][spender] -= subtractedAmount;
}
emit Approval(_msgSender(), spender, _allowances[_msgSender()][spender]);
return true;
}
//--------------------------------------------------------------------------
// RebasingERC20 write methods
/// @inheritdoc IRebasingERC20
function rebase() external override onAfterRebase {
return;
}
//--------------------------------------------------------------------------
// ButtonWrapper write methods
/// @inheritdoc IButtonWrapper
function mint(uint256 amount) external override onAfterRebase returns (uint256) {
uint256 bits = _amountToBits(amount, lastPrice);
uint256 uAmount = _bitsToUAmount(bits);
_deposit(_msgSender(), _msgSender(), uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function mintFor(address to, uint256 amount) external override onAfterRebase returns (uint256) {
uint256 bits = _amountToBits(amount, lastPrice);
uint256 uAmount = _bitsToUAmount(bits);
_deposit(_msgSender(), to, uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function burn(uint256 amount) external override onAfterRebase returns (uint256) {
uint256 bits = _amountToBits(amount, lastPrice);
uint256 uAmount = _bitsToUAmount(bits);
_withdraw(_msgSender(), _msgSender(), uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function burnTo(address to, uint256 amount) external override onAfterRebase returns (uint256) {
uint256 bits = _amountToBits(amount, lastPrice);
uint256 uAmount = _bitsToUAmount(bits);
_withdraw(_msgSender(), to, uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function burnAll() external override onAfterRebase returns (uint256) {
uint256 bits = _accountBits[_msgSender()];
uint256 uAmount = _bitsToUAmount(bits);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), _msgSender(), uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function burnAllTo(address to) external override onAfterRebase returns (uint256) {
uint256 bits = _accountBits[_msgSender()];
uint256 uAmount = _bitsToUAmount(bits);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), to, uAmount, amount, bits);
return uAmount;
}
/// @inheritdoc IButtonWrapper
function deposit(uint256 uAmount) external override onAfterRebase returns (uint256) {
uint256 bits = _uAmountToBits(uAmount);
uint256 amount = _bitsToAmount(bits, lastPrice);
_deposit(_msgSender(), _msgSender(), uAmount, amount, bits);
return amount;
}
/// @inheritdoc IButtonWrapper
function depositFor(address to, uint256 uAmount)
external
override
onAfterRebase
returns (uint256)
{
uint256 bits = _uAmountToBits(uAmount);
uint256 amount = _bitsToAmount(bits, lastPrice);
_deposit(_msgSender(), to, uAmount, amount, bits);
return amount;
}
/// @inheritdoc IButtonWrapper
function withdraw(uint256 uAmount) external override onAfterRebase returns (uint256) {
uint256 bits = _uAmountToBits(uAmount);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), _msgSender(), uAmount, amount, bits);
return amount;
}
/// @inheritdoc IButtonWrapper
function withdrawTo(address to, uint256 uAmount)
external
override
onAfterRebase
returns (uint256)
{
uint256 bits = _uAmountToBits(uAmount);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), to, uAmount, amount, bits);
return amount;
}
/// @inheritdoc IButtonWrapper
function withdrawAll() external override onAfterRebase returns (uint256) {
uint256 bits = _accountBits[_msgSender()];
uint256 uAmount = _bitsToUAmount(bits);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), _msgSender(), uAmount, amount, bits);
return amount;
}
/// @inheritdoc IButtonWrapper
function withdrawAllTo(address to) external override onAfterRebase returns (uint256) {
uint256 bits = _accountBits[_msgSender()];
uint256 uAmount = _bitsToUAmount(bits);
uint256 amount = _bitsToAmount(bits, lastPrice);
_withdraw(_msgSender(), to, uAmount, amount, bits);
return amount;
}
//--------------------------------------------------------------------------
// Private methods
/// @dev Internal method to commit deposit state.
/// NOTE: Expects bits, uAmount, amount to be pre-calculated.
function _deposit(
address from,
address to,
uint256 uAmount,
uint256 amount,
uint256 bits
) private {
require(amount > 0, "ButtonToken: too few button tokens to mint");
IERC20(underlying).safeTransferFrom(from, address(this), uAmount);
_transfer(address(0), to, bits, amount);
}
/// @dev Internal method to commit withdraw state.
/// NOTE: Expects bits, uAmount, amount to be pre-calculated.
function _withdraw(
address from,
address to,
uint256 uAmount,
uint256 amount,
uint256 bits
) private {
require(amount > 0, "ButtonToken: too few button tokens to burn");
_transfer(from, address(0), bits, amount);
IERC20(underlying).safeTransfer(to, uAmount);
}
/// @dev Internal method to commit transfer state.
/// NOTE: Expects bits/amounts to be pre-calculated.
function _transfer(
address from,
address to,
uint256 bits,
uint256 amount
) private {
_accountBits[from] -= bits;
_accountBits[to] += bits;
emit Transfer(from, to, amount);
if (_accountBits[from] == 0) {
delete _accountBits[from];
}
}
/// @dev Updates the `lastPrice` and recomputes the internal scalar.
function _rebase(uint256 price) private {
if (price > MAX_PRICE) {
price = MAX_PRICE;
}
lastPrice = price;
_epoch++;
emit Rebase(_epoch, price);
}
/// @dev Returns the active "un-mined" bits
function _activeBits() private view returns (uint256) {
return TOTAL_BITS - _accountBits[address(0)];
}
/// @dev Queries the oracle for the latest price
/// If fetched oracle price isn't valid returns the last price,
/// else returns the new price from the oracle.
function _queryPrice() private view returns (uint256, bool) {
uint256 newPrice;
bool valid;
(newPrice, valid) = IOracle(oracle).getData();
// Note: we consider newPrice == 0 to be invalid because accounting fails with price == 0
// For example, _bitsPerToken needs to be able to divide by price so a div/0 is caused
return (valid && newPrice > 0 ? newPrice : lastPrice, valid && newPrice > 0);
}
/// @dev Convert button token amount to bits.
function _amountToBits(uint256 amount, uint256 price) private pure returns (uint256) {
return amount * _bitsPerToken(price);
}
/// @dev Convert underlying token amount to bits.
function _uAmountToBits(uint256 uAmount) private pure returns (uint256) {
return uAmount * BITS_PER_UNDERLYING;
}
/// @dev Convert bits to button token amount.
function _bitsToAmount(uint256 bits, uint256 price) private pure returns (uint256) {
return bits / _bitsPerToken(price);
}
/// @dev Convert bits to underlying token amount.
function _bitsToUAmount(uint256 bits) private pure returns (uint256) {
return bits / BITS_PER_UNDERLYING;
}
/// @dev Internal scalar to convert bits to button tokens.
function _bitsPerToken(uint256 price) private pure returns (uint256) {
return PRICE_BITS / price;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
interface IOracle {
function getData() external view returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
import "./IRebasingERC20.sol";
import "./IButtonWrapper.sol";
// Interface definition for the ButtonToken ERC20 wrapper contract
interface IButtonToken is IButtonWrapper, IRebasingERC20 {
/// @dev The reference to the oracle which feeds in the
/// price of the underlying token.
function oracle() external view returns (address);
/// @dev Most recent price recorded from the oracle.
function lastPrice() external view returns (uint256);
/// @dev Update reference to the oracle contract and resets price.
/// @param oracle_ The address of the new oracle.
function updateOracle(address oracle_) external;
/// @dev Log to record changes to the oracle.
/// @param oracle The address of the new oracle.
event OracleUpdated(address oracle);
/// @dev Contract initializer
function initialize(
address underlying_,
string memory name_,
string memory symbol_,
address oracle_
) external;
}
// 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 {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// 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 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: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
// Interface definition for Rebasing ERC20 tokens which have a "elastic" external
// balance and "fixed" internal balance. Each user's external balance is
// represented as a product of a "scalar" and the user's internal balance.
//
// From time to time the "Rebase" event updates scaler,
// which increases/decreases all user balances proportionally.
//
// The standard ERC-20 methods are denominated in the elastic balance
//
interface IRebasingERC20 is IERC20, IERC20Metadata {
/// @notice Returns the fixed balance of the specified address.
/// @param who The address to query.
function scaledBalanceOf(address who) external view returns (uint256);
/// @notice Returns the total fixed supply.
function scaledTotalSupply() external view returns (uint256);
/// @notice Transfer all of the sender's balance to a specified address.
/// @param to The address to transfer to.
/// @return True on success, false otherwise.
function transferAll(address to) external returns (bool);
/// @notice Transfer all balance tokens from one address to another.
/// @param from The address to send tokens from.
/// @param to The address to transfer to.
function transferAllFrom(address from, address to) external returns (bool);
/// @notice Triggers the next rebase, if applicable.
function rebase() external;
/// @notice Event emitted when the balance scalar is updated.
/// @param epoch The number of rebases since inception.
/// @param newScalar The new scalar.
event Rebase(uint256 indexed epoch, uint256 newScalar);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Interface definition for ButtonWrapper contract, which wraps an
// underlying ERC20 token into a new ERC20 with different characteristics.
// NOTE: "uAmount" => underlying token (wrapped) amount and
// "amount" => wrapper token amount
interface IButtonWrapper {
//--------------------------------------------------------------------------
// ButtonWrapper write methods
/// @notice Transfers underlying tokens from {msg.sender} to the contract and
/// mints wrapper tokens.
/// @param amount The amount of wrapper tokens to mint.
/// @return The amount of underlying tokens deposited.
function mint(uint256 amount) external returns (uint256);
/// @notice Transfers underlying tokens from {msg.sender} to the contract and
/// mints wrapper tokens to the specified beneficiary.
/// @param to The beneficiary account.
/// @param amount The amount of wrapper tokens to mint.
/// @return The amount of underlying tokens deposited.
function mintFor(address to, uint256 amount) external returns (uint256);
/// @notice Burns wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @param amount The amount of wrapper tokens to burn.
/// @return The amount of underlying tokens withdrawn.
function burn(uint256 amount) external returns (uint256);
/// @notice Burns wrapper tokens from {msg.sender} and transfers
/// the underlying tokens to the specified beneficiary.
/// @param to The beneficiary account.
/// @param amount The amount of wrapper tokens to burn.
/// @return The amount of underlying tokens withdrawn.
function burnTo(address to, uint256 amount) external returns (uint256);
/// @notice Burns all wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @return The amount of underlying tokens withdrawn.
function burnAll() external returns (uint256);
/// @notice Burns all wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @param to The beneficiary account.
/// @return The amount of underlying tokens withdrawn.
function burnAllTo(address to) external returns (uint256);
/// @notice Transfers underlying tokens from {msg.sender} to the contract and
/// mints wrapper tokens to the specified beneficiary.
/// @param uAmount The amount of underlying tokens to deposit.
/// @return The amount of wrapper tokens mint.
function deposit(uint256 uAmount) external returns (uint256);
/// @notice Transfers underlying tokens from {msg.sender} to the contract and
/// mints wrapper tokens to the specified beneficiary.
/// @param to The beneficiary account.
/// @param uAmount The amount of underlying tokens to deposit.
/// @return The amount of wrapper tokens mint.
function depositFor(address to, uint256 uAmount) external returns (uint256);
/// @notice Burns wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @param uAmount The amount of underlying tokens to withdraw.
/// @return The amount of wrapper tokens burnt.
function withdraw(uint256 uAmount) external returns (uint256);
/// @notice Burns wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back to the specified beneficiary.
/// @param to The beneficiary account.
/// @param uAmount The amount of underlying tokens to withdraw.
/// @return The amount of wrapper tokens burnt.
function withdrawTo(address to, uint256 uAmount) external returns (uint256);
/// @notice Burns all wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @return The amount of wrapper tokens burnt.
function withdrawAll() external returns (uint256);
/// @notice Burns all wrapper tokens from {msg.sender} and transfers
/// the underlying tokens back.
/// @param to The beneficiary account.
/// @return The amount of wrapper tokens burnt.
function withdrawAllTo(address to) external returns (uint256);
//--------------------------------------------------------------------------
// ButtonWrapper view methods
/// @return The address of the underlying token.
function underlying() external view returns (address);
/// @return The total underlying tokens held by the wrapper contract.
function totalUnderlying() external view returns (uint256);
/// @param who The account address.
/// @return The underlying token balance of the account.
function balanceOfUnderlying(address who) external view returns (uint256);
/// @param uAmount The amount of underlying tokens.
/// @return The amount of wrapper tokens exchangeable.
function underlyingToWrapper(uint256 uAmount) external view returns (uint256);
/// @param amount The amount of wrapper tokens.
/// @return The amount of underlying tokens exchangeable.
function wrapperToUnderlying(uint256 amount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
}
}
}
|
@inheritdoc IRebasingERC20
|
function scaledBalanceOf(address account) external view override returns (uint256) {
if (account == address(0)) {
return 0;
}
return _bitsToUAmount(_accountBits[account]);
}
| 86,032
|
/**
*Submitted for verification at Etherscan.io on 2022-02-27
*/
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/NFT.sol
pragma solidity ^0.8.0;
/**
* @dev contract module which defines Bekk NFT NFT Collection
* and all the interactions it uses
*/
contract BornToWhale is ERC1155, Ownable {
//@dev Attributes for NFT configuration
uint256 public tokenId;
uint256 public cost = 72000000000000000;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 10;
uint256 public priceThreshold = 10000;
uint256 internal threshHoldIncrease = 100;
uint256 internal costIncreaseRate = 20;
string public name = "Born to Whale";
bool public paused;
// @dev inner attributes of the contract
/**
* @dev Create an instance of Bekk NFT contract
*/
constructor(
string memory _baseURI
) ERC1155(_baseURI) {
tokenId = 0;
}
/**
* @dev Mint edition to a wallet
* @param _to wallet receiving the edition(s).
* @param _mintAmount number of editions to mint.
*/
function mint(address _to, uint256 _mintAmount) public payable {
require(!paused, "Sales are paused");
require(_mintAmount <= maxMintAmount, "Max amount exceeded");
require(
tokenId + _mintAmount <= maxSupply,
"Not enough mintable editions !"
);
if(msg.sender != owner()){
require(
msg.value == cost * _mintAmount,
"Insufficient transaction amount."
);
}
for (uint256 i = 0; i < _mintAmount; i++) {
tokenId++;
_mint(_to, tokenId, 1, "");
}
if(tokenId >= priceThreshold)
increasePrice();
}
/**
* @dev update price depending on threshold
*/
function increasePrice() internal {
cost = cost * (100 + costIncreaseRate ) / 100;
priceThreshold += threshHoldIncrease;
}
/**
* @dev change cost of NFT
* @param _newCost new cost of each edition
*/
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
/**
* @dev set price increase rate
* @param _costIncreaseRate new cost of each edition
*/
function setPriceIncreaseRate(uint256 _costIncreaseRate) public onlyOwner {
costIncreaseRate = _costIncreaseRate;
}
/**
* @dev set first price threshold for price increase
* @param _priceThreshold new cost of each edition
*/
function setFirstPriceThreshold(uint256 _priceThreshold) public onlyOwner {
priceThreshold = _priceThreshold;
}
/**
* @dev set price threshold for price increase
* @param _tresholdIncrease new cost of each edition
*/
function setThresholdIncrease(uint256 _tresholdIncrease) public onlyOwner {
threshHoldIncrease = _tresholdIncrease;
}
/**
* @dev restrict max mintable amount of edition at a time
* @param _newmaxMintAmount new max mintable amount
*/
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
/**
* @dev restrict max mintable amount of edition at a time
* @param _nexMaxSupply new max supply
*/
function setmaxSupply(uint256 _nexMaxSupply) public onlyOwner {
maxSupply = _nexMaxSupply;
}
/**
* @dev set uri
* @param _newURI new URI
*/
function setURI(string memory _newURI) public onlyOwner {
_setURI(_newURI);
}
/**
* @dev Disable minting process
*/
function pause() public onlyOwner {
paused = !paused;
}
/**
* @dev withdraw balance to owner of the smart contract
*/
function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
}
|
update price depending on threshold/
|
function increasePrice() internal {
cost = cost * (100 + costIncreaseRate ) / 100;
priceThreshold += threshHoldIncrease;
}
| 6,578,779
|
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/proxy/Initializable.sol
// 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) {
return !Address.isContract(address(this));
}
}
// File @openzeppelin/contracts/proxy/Clones.sol
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));
}
}
// File contracts/governance/IMaintainersRegistry.sol
pragma solidity 0.6.12;
interface IMaintainersRegistry {
function isMaintainer(address _address) external view returns (bool);
}
// File contracts/governance/ICongressMembersRegistry.sol
pragma solidity 0.6.12;
/**
* ICongressMembersRegistry contract.
* @author Nikola Madjarevic
* Date created: 13.9.21.
* Github: madjarevicn
*/
interface ICongressMembersRegistry {
function isMember(address _address) external view returns (bool);
function getMinimalQuorum() external view returns (uint256);
}
// File contracts/system/TokensFarmUpgradable.sol
pragma solidity 0.6.12;
//to be fixed
contract TokensFarmUpgradable {
// Address of tokens congress
address public tokensFarmCongress;
// Instance of maintainers registry object
IMaintainersRegistry public maintainersRegistry;
// Only maintainer modifier
modifier onlyMaintainer {
require(
maintainersRegistry.isMaintainer(msg.sender),
"TokensFarmUpgradable: Restricted only to Maintainer"
);
_;
}
// Only tokens farm congress modifier
modifier onlyTokensFarmCongress {
require(
msg.sender == tokensFarmCongress,
"TokensFarmUpgradable: Restricted only to TokensFarmCongress"
);
_;
}
/**
* @notice function to set congress and maintainers registry address
*
* @param _tokensFarmCongress - address of tokens farm congress
* @param _maintainersRegistry - address of maintainers registry
*/
function setCongressAndMaintainersRegistry(
address _tokensFarmCongress,
address _maintainersRegistry
)
internal
{
require(
_tokensFarmCongress != address(0x0),
"tokensFarmCongress can not be 0x0 address"
);
require(
_maintainersRegistry != address(0x0),
"_maintainersRegistry can not be 0x0 address"
);
tokensFarmCongress = _tokensFarmCongress;
maintainersRegistry = IMaintainersRegistry(_maintainersRegistry);
}
/**
* @notice function to set new maintainers registry address
*
* @param _maintainersRegistry - address of new maintainers registry
*/
function setMaintainersRegistry(
address _maintainersRegistry
)
external
onlyTokensFarmCongress
{
require(
_maintainersRegistry != address(0x0),
"_maintainersRegistry can not be 0x0 address"
);
maintainersRegistry = IMaintainersRegistry(_maintainersRegistry);
}
/**
* @notice function to set new congress registry address
*
* @param _tokensFarmCongress - address of new tokens farm congress
*/
function setTokensFarmCongress(
address _tokensFarmCongress
)
external
onlyTokensFarmCongress
{
require(
_tokensFarmCongress != address(0x0),
"_maintainersRegistry can not be 0x0 address"
);
tokensFarmCongress = _tokensFarmCongress;
}
}
// File contracts/interfaces/ITokensFarm.sol
pragma solidity 0.6.12;
interface ITokensFarm {
function fund(uint256 _amount) external;
function setMinTimeToStake(uint256 _minTimeToStake) external;
function setIsEarlyWithdrawAllowed(bool _isEarlyWithdrawAllowed) external;
function setStakeFeePercent(uint256 _stakeFeePercent) external;
function setRewardFeePercent(uint256 _rewardFeePercent) external;
function setFlatFeeAmount(uint256 _flatFeeAmount) external;
function setIsFlatFeeAllowed(bool _isFlatFeeAllowed) external;
function withdrawCollectedFeesERC() external;
function withdrawCollectedFeesETH() external;
function withdrawTokensIfStuck(address _erc20, uint256 _amount, address _beneficiary) external;
function initialize(
address _erc20, uint256 _rewardPerSecond, uint256 _startTime, uint256 _minTimeToStake,
bool _isEarlyWithdrawAllowed, uint256 _penalty, address _tokenStaked, uint256 _stakeFeePercent,
uint256 _rewardFeePercent, uint256 _flatFeeAmount, address payable _feeCollector, bool _isFlatFeeAllowed,
address _farmImplementation
) external;
function setFeeCollector(address payable _feeCollector) external ;
}
// File contracts/TokensFarmFactory.sol
pragma solidity 0.6.12;
contract TokensFarmFactory is TokensFarmUpgradable, Initializable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Clones for *;
// Array of Tokens Farm that are deployed
address[] public deployedTokensFarms;
// FeeCollector + CongressAddress
address payable public feeCollector;
// Address of deployed tokens farm contract
address public farmImplementation;
// Events
event DeployedFarm(address indexed farmAddress);
event TokensFarmImplementationSet(address indexed farmImplementation);
event FeeCollectorSet(address indexed feeCollector);
/**
* @notice function sets initial state of contract
*
* @param _farmImplementation- address of deployed farm
* @param _tokensFarmCongress - address of farm congress
* @param _maintainersRegistry - address of maintainers registry
* @param _feeCollector - address of feeCollector
*/
function initialize(
address _farmImplementation,
address _tokensFarmCongress,
address _maintainersRegistry,
address payable _feeCollector
)
external
initializer
{
require(
_farmImplementation != address(0),
"farmImplementation can not be 0x0 address"
);
require(
_feeCollector != address(0),
"_feeCollector can not be 0x0 address"
);
// set congress and maintainers registry address
setCongressAndMaintainersRegistry(
_tokensFarmCongress,
_maintainersRegistry
);
// address of fee collector
feeCollector = _feeCollector;
// address of tokens farm contract
farmImplementation = _farmImplementation;
}
/**
* @notice function funds the farm
*
* @param _farmAddress - function will operate on
* farm with this address
* @param _rewardToken - address of reward token
* @param _amount - funding the farm with this amount of tokens
*/
function _fundInternal(
address _farmAddress,
address _rewardToken,
uint256 _amount
)
internal
{
require(
_farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
// instance of erc20 contract
IERC20 rewardToken = IERC20(_rewardToken);
// approval of transaction
rewardToken.approve(_farmAddress, _amount);
ITokensFarm tokensFarm = ITokensFarm(_farmAddress);
tokensFarm.fund(_amount);
}
/**
* @notice function to check does factory has enough funds
*
* @param _rewardToken - address of reward token
* @param _totalBudget - funding the farm
* with this amount of tokens
*/
function _sufficientFunds(
address _rewardToken,
uint256 _totalBudget
)
internal
view
returns(bool)
{
// instance of erc20 contract
IERC20 rewardToken = IERC20(_rewardToken);
return rewardToken.balanceOf(address(this)) >= _totalBudget;
}
/**
* @notice function deploys and funds farms
*
* @dev store their addresses in array
* @dev deploys tokens farm proxy contract
* @dev initializing of contract
*
* @param _rewardToken - address of reward token
* @param _rewardPerSecond - number of reward per second
* @param _minTimeToStake - how much time needs to past before staking
* @param _isEarlyWithdrawAllowed - is early withdraw allowed or not
* @param _penalty - ENUM(what type of penalty)
* @param _tokenStaked - address of token which is staked
* @param _stakeFeePercent - fee percent for staking
* @param _rewardFeePercent - fee percent for reward distribution
* @param _flatFeeAmount - flat fee amount
* @param _isFlatFeeAllowed - is flat fee allowed or not
*/
function deployAndFundTokensFarm(
address _rewardToken,
uint256 _rewardPerSecond,
uint256 _minTimeToStake,
bool _isEarlyWithdrawAllowed,
uint256 _penalty,
address _tokenStaked,
uint256 _stakeFeePercent,
uint256 _rewardFeePercent,
uint256 _flatFeeAmount,
bool _isFlatFeeAllowed,
uint256 _totalBudget
)
external
onlyMaintainer
{
require(
_sufficientFunds(_rewardToken, _totalBudget),
"There is not enough tokens left in factory to fund"
);
// Creates clone of TokensFarm smart contract
address clone = Clones.clone(farmImplementation);
// Deploy tokens farm;
ITokensFarm(clone).initialize(
_rewardToken,
_rewardPerSecond,
block.timestamp + 10,
_minTimeToStake,
_isEarlyWithdrawAllowed,
_penalty,
_tokenStaked,
_stakeFeePercent,
_rewardFeePercent,
_flatFeeAmount,
feeCollector,
_isFlatFeeAllowed,
farmImplementation
);
// Add deployed farm to array of deployed farms
deployedTokensFarms.push(clone);
// Funding the farm
_fundInternal(clone, _rewardToken, _totalBudget);
// Emits event with farms address
emit DeployedFarm(clone);
}
/**
* @notice function funds again the farm if necessary
*
* @param farmAddress - function will operate
* on farm with this address
* param rewardToken - address of reward token
* @param amount - funding the farm with this amount of tokens
*/
function fundTheSpecificFarm(
address farmAddress,
address rewardToken,
uint256 amount
)
external
onlyMaintainer
{
_fundInternal(farmAddress, rewardToken, amount);
}
/**
* @notice function withdraws collected fees in ERC value
*
* @param farmAddress - function will operate on
* farm with this address
*/
function withdrawCollectedFeesERCOnSpecificFarm(
address farmAddress
)
external
onlyTokensFarmCongress
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.withdrawCollectedFeesERC();
}
/**
* @notice function withdraws collected fees in ETH value
*
* @param farmAddress - function will operate on
* farm with this address
*/
function withdrawCollectedFeesETHOnSpecificFarm(
address farmAddress
)
external
onlyTokensFarmCongress
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.withdrawCollectedFeesETH();
}
/**
* @notice function withdraws stuck tokens on farm
*
* @param farmAddress - function will operate on
* farm with this address
* @param _erc20 - address of token that is stuck
* @param _amount - how many was deposited
* @param _beneficiary - address of user
* that deposited by mistake
*/
function withdrawTokensIfStuckOnSpecificFarm(
address farmAddress,
address _erc20,
uint256 _amount,
address _beneficiary
)
external
onlyTokensFarmCongress
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.withdrawTokensIfStuck(_erc20, _amount, _beneficiary);
}
/**
* @notice function is setting address of deployed
* tokens farm contract
*
* @param _farmImplementation - address of new tokens farm contract
*/
function setTokensFarmImplementation(
address _farmImplementation
)
external
onlyTokensFarmCongress
{
require(
_farmImplementation != address(0),
"farmImplementation can not be 0x0 address"
);
farmImplementation = _farmImplementation;
emit TokensFarmImplementationSet(farmImplementation);
}
/**
* @notice function is setting new address of fee collector
*
* @param _feeCollector - address of new fee collector
*/
function setFeeCollector(
address payable _feeCollector
)
external
onlyTokensFarmCongress
{
require(
_feeCollector != address(0),
"Fee Collector can not be 0x0 address"
);
feeCollector = _feeCollector;
emit FeeCollectorSet(feeCollector);
}
/**
* @notice function is setting new address of fee collector
* on active farm
*
* @param farmAddress - address of farm
*/
function setCurrentFeeCollectorOnSpecificFarm(
address farmAddress
)
external
onlyTokensFarmCongress
{
require(
farmAddress != address(0x0),
"Farm address can not be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setFeeCollector(feeCollector);
}
/**
* @notice function is setting variable minTimeToStake in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _minTimeToStake - value of variable that needs to be set
*/
function setMinTimeToStakeOnSpecificFarm(
address farmAddress,
uint256 _minTimeToStake
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
require(_minTimeToStake >= 0, "Minimal time can't be under 0");
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setMinTimeToStake(_minTimeToStake);
}
/**
* @notice function is setting state if isEarlyWithdrawAllowed in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _isEarlyWithdrawAllowed - state of variable that needs to be set
*/
function setIsEarlyWithdrawAllowedOnSpecificFarm(
address farmAddress,
bool _isEarlyWithdrawAllowed
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setIsEarlyWithdrawAllowed(_isEarlyWithdrawAllowed);
}
/**
* @notice function is setting variable stakeFeePercent in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _stakeFeePercent - value of variable that needs to be set
*/
function setStakeFeePercentOnSpecificFarm(
address farmAddress,
uint256 _stakeFeePercent
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
require(
_stakeFeePercent > 0 && _stakeFeePercent < 100,
"Stake fee percent must be between 0 and 100"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setStakeFeePercent(_stakeFeePercent);
}
/**
* @notice function is setting variable rewardFeePercent in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _rewardFeePercent - value of variable that needs to be set
*/
function setRewardFeePercentOnSpecificFarm(
address farmAddress,
uint256 _rewardFeePercent
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
require(
_rewardFeePercent > 0 && _rewardFeePercent < 100,
"Reward fee percent must be between 0 and 100"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setRewardFeePercent(_rewardFeePercent);
}
/**
* @notice function is setting variable flatFeeAmount in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _flatFeeAmount - value of variable that needs to be set
*/
function setFlatFeeAmountOnSpecificFarm(
address farmAddress,
uint256 _flatFeeAmount
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
require(_flatFeeAmount >= 0, "Flat fee can't be under 0");
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setFlatFeeAmount(_flatFeeAmount);
}
/**
* @notice function is setting variable isFlatFeeAllowed in tokens farm
*
* @param farmAddress - function will operate on farm with this address
* @param _isFlatFeeAllowed - state of variable that needs to be set
*/
function setIsFlatFeeAllowedOnSpecificFarm(
address farmAddress,
bool _isFlatFeeAllowed
)
external
onlyMaintainer
{
require(
farmAddress != address(0x0),
"Farm's address can't be 0x0 address"
);
ITokensFarm tokensFarm = ITokensFarm(farmAddress);
tokensFarm.setIsFlatFeeAllowed(_isFlatFeeAllowed);
}
/**
* @notice function returns address of last deployed farm
*
* @dev can be used on BE as additional checksum next to event emitted in tx
*
* @return address of last deployed farm
*/
function getLastDeployedFarm()
external
view
returns (address)
{
if (deployedTokensFarms.length == 0) {
// Means no farms deployed yet.
return address(0);
}
// Deployed last deployed farm.
return deployedTokensFarms[deployedTokensFarms.length - 1];
}
/**
* @notice function returns array,
* of deployed farms(from start to end)
*
* @param start - beginning index of array
* @param end - ending index of array
*
* @return array made of address of deployed tokens farm
*/
function getDeployedTokensFarm(
uint256 start,
uint256 end
)
external
view
returns (address[] memory)
{
require(start < end, "Start should be less than end");
require(
start >= 0 && end <= deployedTokensFarms.length,
"One of the index is out of range"
);
address[] memory tokensFarms = new address[](end - start);
uint256 counter;
for (uint256 i = start; i < end; i++) {
tokensFarms[counter] = deployedTokensFarms[i];
counter++;
}
return tokensFarms;
}
}
|
function funds again the farm if necessary farmAddress - function will operate on farm with this address param rewardToken - address of reward token amount - funding the farm with this amount of tokens/
|
function fundTheSpecificFarm(
address farmAddress,
address rewardToken,
uint256 amount
)
external
onlyMaintainer
{
_fundInternal(farmAddress, rewardToken, amount);
}
| 11,958,854
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IYieldOraclelizable.sol";
import "./IYieldOracle.sol";
// a modified version of https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol
// sliding window oracle that uses observations collected over a window to provide moving yield averages in the past
// `windowSize` with a precision of `windowSize / granularity`
contract YieldOracle is IYieldOracle {
using SafeMath for uint256;
IYieldOraclelizable public cumulator;
struct Observation {
uint256 timestamp;
uint256 yieldCumulative;
}
// the desired amount of time over which the moving average should be computed, e.g. 24 hours
uint256 public immutable windowSize;
// the number of observations stored for each pair, i.e. how many price observations are stored for the window.
// as granularity increases from 1, more frequent updates are needed, but moving averages become more precise.
// averages are computed over intervals with sizes in the range:
// [windowSize - (windowSize / granularity) * 2, windowSize]
// e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for
// the period:
// [now - [22 hours, 24 hours], now]
uint8 public immutable granularity;
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint256 public immutable periodSize;
// list of yield observations
Observation[] public yieldObservations;
constructor(
address cumulator_,
uint256 windowSize_,
uint8 granularity_
) {
require(granularity_ > 1, "YO: GRANULARITY");
require(
(periodSize = windowSize_ / granularity_) * granularity_ ==
windowSize_,
"YO: WINDOW_NOT_EVENLY_DIVISIBLE"
);
windowSize = windowSize_;
granularity = granularity_;
cumulator = IYieldOraclelizable(cumulator_);
for (uint256 i = yieldObservations.length; i < granularity_; i++) {
yieldObservations.push();
}
}
// returns the index of the observation corresponding to the given timestamp
function observationIndexOf(uint256 timestamp_)
public
view
returns (uint8 index)
{
uint256 epochPeriod = timestamp_ / periodSize;
return uint8(epochPeriod % granularity);
}
// returns the observation from the oldest epoch (at the beginning of the window) relative to the current time
function getFirstObservationInWindow()
private
view
returns (Observation storage firstObservation)
{
uint8 observationIndex = observationIndexOf(block.timestamp);
// no overflow issue. if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = yieldObservations[firstObservationIndex];
}
// update the cumulative price for the observation at the current timestamp. each observation is updated at most
// once per epoch period.
function update() external virtual override {
// get the observation for the current period
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = yieldObservations[observationIndex];
// we only want to commit updates once per period (i.e. windowSize / granularity)
uint256 timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed > periodSize) {
(uint256 yieldCumulative) = cumulator.cumulatives();
observation.timestamp = block.timestamp;
observation.yieldCumulative = yieldCumulative;
}
}
// given the cumulative yields of the start and end of a period, and the length of the period (timeElapsed in seconds), compute the average
// yield and extrapolate it for forInterval (seconds) in terms of how much amount out is received for the amount in
function computeAmountOut(
uint256 yieldCumulativeStart_,
uint256 yieldCumulativeEnd_,
uint256 timeElapsed_,
uint256 forInterval_
) private pure returns (uint256 yieldAverage) {
// ((yieldCumulativeEnd_ - yieldCumulativeStart_) * forInterval_) / timeElapsed_;
return yieldCumulativeEnd_.sub(yieldCumulativeStart_).mul(forInterval_).div(timeElapsed_);
}
// returns the amount out corresponding to the amount in for a given token using the moving average over the time
// range [now - [windowSize, windowSize - periodSize * 2], now]
// update must have been called for the bucket corresponding to timestamp `now - windowSize`
function consult(uint256 forInterval)
external
override
virtual
returns (uint256 yieldForInterval)
{
Observation storage firstObservation = getFirstObservationInWindow();
uint256 timeElapsed = block.timestamp - firstObservation.timestamp;
if (!(timeElapsed <= windowSize)) {
// originally:
// require(
// timeElapsed <= windowSize,
// "YO: MISSING_HISTORICAL_OBSERVATION"
// );
// if the oracle is falling behind, it reports 0 yield => there's no incentive to buy sBOND
return 0;
}
if (!(timeElapsed >= windowSize - periodSize * 2)) {
// originally:
// should never happen.
// require(
// timeElapsed >= windowSize - periodSize * 2,
// "YO: UNEXPECTED_TIME_ELAPSED"
// );
// if the oracle is in an odd state, it reports 0 yield => there's no incentive to buy sBOND
return 0;
}
(uint256 yieldCumulative) = cumulator.cumulatives();
return
computeAmountOut(
firstObservation.yieldCumulative,
yieldCumulative,
timeElapsed,
forInterval
);
}
}
// 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: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOraclelizable {
// accumulates/updates internal state and returns cumulatives
// oracle should call this when updating
function cumulatives()
external
returns(uint256 cumulativeYield);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOracle {
function update() external;
function consult(uint256 forInterval) external returns (uint256 amountOut);
}
|
returns the observation from the oldest epoch (at the beginning of the window) relative to the current time no overflow issue. if observationIndex + 1 overflows, result is still zero.
|
function getFirstObservationInWindow()
private
view
returns (Observation storage firstObservation)
{
uint8 observationIndex = observationIndexOf(block.timestamp);
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = yieldObservations[firstObservationIndex];
}
| 1,295,886
|
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../lib/ABDKMath64x64.sol";
import "../interfaces/IAssimilator.sol";
import "../interfaces/IOracle.sol";
contract NzdsToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IOracle private constant oracle = IOracle(0x3977CFc9e4f29C184D4675f4EB8e0013236e5f3e);
IERC20 private constant nzds = IERC20(0xDa446fAd08277B4D2591536F204E018f32B6831c);
// solhint-disable-next-line
constructor() {}
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
uint256 _balance = nzds.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
}
// takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return 0;
// 1e6
_nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/nzds-transfer-failed");
}
// takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _nzdsAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount);
require(_transferSuccess, "Curve/nzds-transfer-failed");
uint256 _balance = nzds.balanceOf(address(this));
amount_ = _nzdsAmount.divu(1e6);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _nzdsAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount);
require(_transferSuccess, "Curve/nzds-transfer-failed");
amount_ = _nzdsAmount.divu(1e6);
}
// takes a numeraire value of nzds, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = nzds.transfer(_dst, amount_);
require(_transferSuccess, "Curve/nzds-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
}
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return 0;
// 1e6
_nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = nzds.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
uint256 _balance = nzds.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio
// Mainly to protect LP from losing
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e18).div(_nzdsBal.mul(1e18).div(_baseWeight));
balance_ = ((_nzdsBal * _rate) / 1e6).divu(1e18);
}
}
|
views the numeraire value of the current balance of the reserve, in this case nzds instead of calculating with chainlink's "rate" it'll be determined by the existing token ratio Mainly to protect LP from losing Rate is in 1e6
|
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
uint256 _rate = _usdcBal.mul(1e18).div(_nzdsBal.mul(1e18).div(_baseWeight));
balance_ = ((_nzdsBal * _rate) / 1e6).divu(1e18);
}
| 12,659,194
|
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract 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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
function mint(address from, address to, uint tokens) public;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract MusicContract {
using SafeMath for uint256;
struct Music {
address musician;
uint musicId;
string musicLink;
bool marketType; //false for sponsor, true for votes
uint totalAmountForUnlock;
uint totalEarning;
uint amountLeftForUnlock;
uint amountToBePaid;
bool isUnlocked;
}
struct Voter {
address publicKey;
uint amountEarned;
}
struct Sponsor {
address publicKey;
uint amountEarned;
uint amountPaid;
}
struct VoteMusicPayoutScheme {
uint musicianPercentage; //57
uint voterPercentage;// 35
uint systemPercentage;// 8
}
struct SponsorPayoutScheme {
uint sponsorPercentage;// 45
uint musicianPercentage;// 37
uint voterPercentage; // 10
uint systemPercentage; // 8
}
// The token that would be sold using this contract
ERC20Interface public token;
//Objects for use within program
VoteMusicPayoutScheme voteMusicPayoutSchemeObj;
SponsorPayoutScheme sponsorPayoutSchemeObj;
Music music;
Sponsor sponsor;
Voter voter;
uint counter = 0;
address public wallet;
mapping (uint=>Voter[]) musicVoterList;
mapping (uint=>Sponsor[]) musicSponsorList;
mapping (uint=>Music) musicList;
uint localIntAsPerNeed;
address localAddressAsPerNeed;
Voter[] voters;
Sponsor[] sponsors;
function MusicContract(address _wallet,address _tokenAddress) public {
wallet = _wallet;
token = ERC20Interface(_tokenAddress);
setup();
}
// fallback function can be used to buy tokens
function () public payable {
revert();
}
function setup() internal {
voteMusicPayoutSchemeObj = VoteMusicPayoutScheme({musicianPercentage:57, voterPercentage:35, systemPercentage:8});
sponsorPayoutSchemeObj = SponsorPayoutScheme({sponsorPercentage:45, musicianPercentage: 37, voterPercentage:10, systemPercentage:8});
}
function UploadMusic(uint muId, string lnk, address muPublicKey,bool unlocktype,uint amount, uint uploadTokenAmount) public
{
require(msg.sender == wallet);
token.mint(muPublicKey,wallet,uploadTokenAmount*10**18); //tokens deducted from advertiser's wallet
require(musicList[muId].musicId == 0);
//Add to music struct
music = Music ({
musician : muPublicKey,
musicId : muId,
musicLink : lnk,
marketType : unlocktype,
totalEarning : 0,
totalAmountForUnlock : amount * 10 ** 18,
amountLeftForUnlock : amount * 10 ** 18,
amountToBePaid : uploadTokenAmount * 10 **18,
isUnlocked : false
});
musicList[muId] = music;
}
function DownloadMusic(uint musId, address senderId, uint tokenAmount) public returns (bool goAhead)
{
require(msg.sender == wallet);
require(musicList[musId].musicId == musId);
require(musicList[musId].isUnlocked == true);
token.mint(senderId,wallet,tokenAmount*10**18);
musicList[musId].totalEarning = musicList[musId].totalEarning.add(tokenAmount);
musicList[musId].amountToBePaid = musicList[musId].amountToBePaid.add(tokenAmount);
goAhead = true;
}
function DoSponsorPayout(Music musicObj) private
{
//logString("In sponsor payout function");
//sponsor
localIntAsPerNeed = musicObj.musicId;
sponsors = musicSponsorList[localIntAsPerNeed];
//calculating sponsor payout
localIntAsPerNeed = sponsorPayoutSchemeObj.sponsorPercentage;
uint sponsorPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
sponsorPayout = sponsorPayout.div(100);
//calculating voter payout
voters = musicVoterList[musicObj.musicId];
localIntAsPerNeed = sponsorPayoutSchemeObj.voterPercentage;
uint voterPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
voterPayout = voterPayout.div(100);
//calculating musician payout
localIntAsPerNeed = sponsorPayoutSchemeObj.musicianPercentage;
uint musicianPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
musicianPayout = musicianPayout.div(100);
//calculating system payout
localIntAsPerNeed = sponsorPayoutSchemeObj.systemPercentage;
uint systemPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
systemPayout = systemPayout.div(100);
//doing sponsor payout
for (counter=0;counter<sponsors.length;counter++)
{
//Find the percentage
localIntAsPerNeed = sponsors[counter].amountPaid.mul(100);
localIntAsPerNeed = localIntAsPerNeed.div(musicObj.totalAmountForUnlock);
uint amtToSend = sponsorPayout.mul(localIntAsPerNeed);
amtToSend = amtToSend.div(100);
token.mint(wallet, sponsors[counter].publicKey, amtToSend);
sponsors[counter].amountEarned = sponsors[counter].amountEarned.add(amtToSend);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(amtToSend);
}
//logString("paid out to sponsors");
//doing voter payout
if (voters.length>0)
{
uint perVoterPayout = voterPayout.div(voters.length);
for (counter=0;counter<voters.length;counter++)
{
token.mint(wallet, voters[counter].publicKey, perVoterPayout);
voters[counter].amountEarned = voters[counter].amountEarned.add(perVoterPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(perVoterPayout);
}
//logString("paid out to voters");
}
else
{
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(voterPayout);
}
//doing musician payout
localAddressAsPerNeed = musicObj.musician;
token.mint(wallet,localAddressAsPerNeed,musicianPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(musicianPayout);
//logString("paid out to musicians");
//catering for system payout - no token transfers as the tokens are already in the owner wallet
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(systemPayout);
//logString("paid out to system");
require(musicObj.amountToBePaid == 0);
}
function DoVoterPayout(Music musicObj) private
{
uint j = 0;
//sponsor
//logString("In voter payout function");
//calculating voter payout
voters = musicVoterList[musicObj.musicId];
localIntAsPerNeed = voteMusicPayoutSchemeObj.voterPercentage;
uint voterPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
voterPayout = voterPayout.div(100);
uint perVoterPayout = voterPayout.div(voters.length);
//calculating musician payout
localIntAsPerNeed = voteMusicPayoutSchemeObj.musicianPercentage;
uint musicianPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
musicianPayout = musicianPayout.div(100);
//calculating system payout
localIntAsPerNeed = voteMusicPayoutSchemeObj.systemPercentage;
uint systemPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
systemPayout = systemPayout.div(100);
//doing voter payout
for (j=0;j<voters.length;j++)
{
token.mint(wallet,voters[j].publicKey, perVoterPayout);
voters[j].amountEarned = voters[j].amountEarned.add(perVoterPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(perVoterPayout);
}
//logString("voter payout done");
//doing musician payout
token.mint(wallet,musicObj.musician,musicianPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(musicianPayout);
//logString("musician payout done");
//catering for system payout - not doing manual transfer as all the tokens are already in the wallet
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(systemPayout);
//logString("system payout done");
require(musicObj.amountToBePaid == 0);
}
function DoMusicPayout (uint musId) public
{
require(msg.sender == wallet);
require(musicList[musId].musicId == musId);
require(musicList[musId].isUnlocked == true);
require(musicList[musId].amountToBePaid > 0);
require(token.balanceOf(wallet)>=musicList[musId].amountToBePaid);
//logString("In music payout");
bool unlock = musicList[musId].marketType;
if (unlock == false)
{
//unlock type is sponsor
//logString("Unlock type is sponsor");
DoSponsorPayout(musicList[musId]);
musicList[musId].amountToBePaid = 0;
}
else
{
//unlock type is voter
//logString("Unlock type is voter");
DoVoterPayout(musicList[musId]);
musicList[musId].amountToBePaid = 0;
}
}
function SponsorMusic(uint musId, uint sponsorAmount, address sponsorAddress) public
{
//msg.sender is the sponsor
sponsorAmount = sponsorAmount * 10 ** 18;
require(token.balanceOf(sponsorAddress) > sponsorAmount);
require (musicList[musId].musicId == musId);
require (musicList[musId].isUnlocked == false);
require(musicList[musId].marketType == false);
require (musicList[musId].amountLeftForUnlock>=sponsorAmount);
token.mint(sponsorAddress,wallet,sponsorAmount);
//logString("sufficient payment done");
musicList[musId].amountLeftForUnlock = musicList[musId].amountLeftForUnlock.sub(sponsorAmount);
musicList[musId].amountToBePaid = musicList[musId].amountToBePaid.add(sponsorAmount);
sponsor = Sponsor({
publicKey : msg.sender,
amountEarned : 0,
amountPaid : sponsorAmount
});
musicSponsorList[musId].push(sponsor);
//logString("sponsor added");
if (musicList[musId].amountLeftForUnlock == 0)
{
musicList[musId].isUnlocked = true;
//logString("music unlocked");
}
}
function VoteMusic(uint musId, address voterPublicKey) public
{
require(musicList[musId].musicId == musId);
require(musicList[musId].isUnlocked == false);
//logString("music found");
voter = Voter({publicKey: voterPublicKey, amountEarned : 0});
musicVoterList[musId].push(voter);
//logString("voter added");
}
function unlockVoterMusic(uint musId) public
{
require(msg.sender == wallet);
require(musicList[musId].musicId == musId);
musicList[musId].isUnlocked = true;
}
function getTokenBalance() public constant returns (uint) {
return token.balanceOf(msg.sender);
}
function changeWalletAddress(address newWallet) public
{
require(msg.sender == wallet);
wallet = newWallet;
}
}
|
logString("In sponsor payout function");sponsorcalculating sponsor payoutcalculating voter payoutcalculating musician payoutcalculating system payoutdoing sponsor payoutFind the percentage
|
function DoSponsorPayout(Music musicObj) private
{
localIntAsPerNeed = musicObj.musicId;
sponsors = musicSponsorList[localIntAsPerNeed];
localIntAsPerNeed = sponsorPayoutSchemeObj.sponsorPercentage;
uint sponsorPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
sponsorPayout = sponsorPayout.div(100);
voters = musicVoterList[musicObj.musicId];
localIntAsPerNeed = sponsorPayoutSchemeObj.voterPercentage;
uint voterPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
voterPayout = voterPayout.div(100);
localIntAsPerNeed = sponsorPayoutSchemeObj.musicianPercentage;
uint musicianPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
musicianPayout = musicianPayout.div(100);
localIntAsPerNeed = sponsorPayoutSchemeObj.systemPercentage;
uint systemPayout = musicObj.amountToBePaid.mul(localIntAsPerNeed);
systemPayout = systemPayout.div(100);
for (counter=0;counter<sponsors.length;counter++)
{
localIntAsPerNeed = sponsors[counter].amountPaid.mul(100);
localIntAsPerNeed = localIntAsPerNeed.div(musicObj.totalAmountForUnlock);
uint amtToSend = sponsorPayout.mul(localIntAsPerNeed);
amtToSend = amtToSend.div(100);
token.mint(wallet, sponsors[counter].publicKey, amtToSend);
sponsors[counter].amountEarned = sponsors[counter].amountEarned.add(amtToSend);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(amtToSend);
}
{
uint perVoterPayout = voterPayout.div(voters.length);
for (counter=0;counter<voters.length;counter++)
{
token.mint(wallet, voters[counter].publicKey, perVoterPayout);
voters[counter].amountEarned = voters[counter].amountEarned.add(perVoterPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(perVoterPayout);
}
else
{
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(voterPayout);
}
token.mint(wallet,localAddressAsPerNeed,musicianPayout);
musicObj.amountToBePaid = musicObj.amountToBePaid.sub(musicianPayout);
require(musicObj.amountToBePaid == 0);
}
| 12,627,114
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IBEP20.sol";
import "./EIP918Interface.sol";
import "./interface/ApproveAndCallFallBack.sol";
import "openzeppelin-solidity/contracts/GSN/Context.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/proxy/Initializable.sol";
contract BEP20ArmacoinImplementationV1 is Context, IBEP20, EIP918Interface, Initializable {
using SafeMath for uint256;
/**
* @dev Mapping for storing messages and price for message
*/
mapping(address => string) private _messages;
uint256 private _MessageFee;
event MessageFeeSet(uint256 fee);
/**
* @dev Sets initial minining parameters
*/
uint256 public latestDifficultyPeriodStarted;
uint256 public epochCount;//number of 'blocks' mined
//a little number
uint256 public _MINIMUM_TARGET = power(2,16);
//a big number is easier ; just find a solution that is smaller
uint256 public _MAXIMUM_TARGET = power(2,224); //bitcoin uses 224
uint256 public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
address public lastRewardTo;
uint256 public lastRewardAmount;
uint256 public lastRewardEthBlockNumber;
// a bunch of maps to know where this is going (pun intended)
uint256 public _MAX_MESSAGE_LENGTH = 360;
//
mapping(bytes32 => bytes32) public solutionForChallenge;
mapping(uint256 => uint256) public targetForEpoch;
mapping(uint256 => uint256) public timeStampForEpoch;
/**
* @dev BEP compliant variables
*/
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 public _maxSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
bool private _mintable;
bool private _mineable;
constructor() public {
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev sets initials supply, owner, minting and mining opions
*/
function initialize(string memory name, string memory symbol, uint8 decimals, uint256 amount, uint256 maxSupply, bool mintable, bool mineable, address owner) public initializer {
_owner = owner;
_name = name;
_symbol = symbol;
_decimals = decimals;
_mintable = mintable;
_maxSupply = uint256(maxSupply).mul(power(10,uint256(decimals)));
//
require(amount <= _maxSupply,"Armacoin: The amount should not exceed maximum supply");
_mineable = mineable;
_mint(owner, amount);
//
_MessageFee = 0;
//
targetForEpoch[epochCount] = _MAXIMUM_TARGET;
challengeNumber = "GENESIS_BLOCK";
solutionForChallenge[challengeNumber] = "42"; // ahah yes
timeStampForEpoch[epochCount] = block.timestamp;
latestDifficultyPeriodStarted = block.number;
epochCount = epochCount.add(1);
targetForEpoch[epochCount] = _MAXIMUM_TARGET;
miningTarget = _MAXIMUM_TARGET;
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Returns if the token is mintable or not
*/
function mintable() external view returns (bool) {
return _mintable;
}
/**
* @dev Returns if the token is mineable or not
*/
function mineable() external view returns (bool){
return _mineable;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return _owner;
}
/**
* @dev Returns the token decimals.
*/
function decimals() external override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external override view returns (string memory) {
return _name;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() external override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) external override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev
* @notice `msg.sender` approves `_spender` to send `_amount` tokens on
* its behalf, and then a function is triggered in the contract that is
* being approved, `_spender`. This allows users to use their tokens to
* interact with contracts in one function call instead of two
*
* Requirements:
*
* - `spender` The address of the contract able to transfer the tokens
* - `_amount` The amount of tokens to be approved for transfer
* - `_extraData` The raw data for call another contract
* - return True if the function call was successful
*/
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success) {
_approve(_msgSender(), address(_spender), _amount);
_spender.receiveApproval(
msg.sender,
_amount,
_extraData
);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* 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) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
* - `_mintable` must be true
*/
function mint(uint256 amount) external onlyOwner returns (bool) {
require(_mintable, "This token is not mintable");
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates tokens by means of POW mining algorithm, increasing
* total supply.
*/
function mine(uint256 nonce, bytes32 challenge_digest) public override returns (bool success){
require(_mineable, "Armacoin: This token is not mineable");
//the PoW must contain work that includes a recent ethereum (BSC) block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challenge_digest];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint256 reward_amount = getMiningReward();
// minting limit is _maxSupply
require(_totalSupply.add(reward_amount) <= _maxSupply);
_balances[msg.sender] = _balances[msg.sender].add(reward_amount);
_totalSupply = _totalSupply.add(reward_amount);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
emit Mint(msg.sender, reward_amount, epochCount, challengeNumber);
return true;
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal {
timeStampForEpoch[epochCount] = block.timestamp;
epochCount = epochCount.add(1);
//Difficulty adjustment following the DigiChieldv3 implementation (Tempered-SMA)
// Allows more thorough protection against multi-pool hash attacks
// https://github.com/zawy12/difficulty-algorithms/issues/9
miningTarget = _reAdjustDifficulty(epochCount);
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = blockhash(block.number.sub(1));
}
//https://github.com/zawy12/difficulty-algorithms/issues/21
//readjust the target via a tempered EMA
function _reAdjustDifficulty(uint256 _epoch) internal returns (uint256) {
uint256 timeTarget = 300; // We want miners to spend 5 minutes to mine each 'block'
uint256 N = 6180; //N = 1000*n, ratio between timeTarget and windowTime (31-ish minutes)
// (Ethereum doesn't handle floating point numbers very well)
uint256 elapsedTime = timeStampForEpoch[_epoch.sub(1)].sub(timeStampForEpoch[_epoch.sub(2)]); // will revert if current timestamp is smaller than the previous one
targetForEpoch[_epoch] = (targetForEpoch[_epoch.sub(1)].mul(10000)).div( N.mul(3920).div(N.sub(1000).add(elapsedTime.mul(1042).div(timeTarget))).add(N));
// newTarget = Tampered EMA-retarget on the last 6 blocks (a bit more, it's an approximation)
// Also, there's an adjust factor, in order to correct the delays induced by the time it takes for transactions to confirm
// Difficulty is adjusted to the time it takes to produce a valid hash. Here, if we set it to take 300 seconds, it will actually take
// 300 seconds + TxConfirmTime to validate that block. So, we wad a little % to correct that lag time.
// Once Ethereum scales, it will actually make block times go a tad faster. There's no perfect answer to this problem at the moment
latestDifficultyPeriodStarted = block.number;
return targetForEpoch[_epoch];
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public view override returns (bytes32) {
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public view override returns (uint256) {
return _MAXIMUM_TARGET.div(targetForEpoch[epochCount]);
}
// mining target
function getMiningTarget() public view override returns (uint256) {
return targetForEpoch[epochCount];
}
// SafeMath like power calculations
function power(uint256 n, uint256 e) internal pure returns (uint256) {
if (e == 0) {
return 1;
} else if (e == 1) {
return n;
} else {
uint256 p = power(n, e.div(2));
p = p.mul(p);
if (e.mod(2) == 1) {
p = p.mul(n);
}
return p;
}
}
//There's no limit to the coin supply
//reward follows more or less the same emmission rate as coins'. 5 minutes per block / 105120 block in one year (roughly)
function getMiningReward() public view override returns (uint256) {
bytes32 digest = solutionForChallenge[challengeNumber];
if(epochCount > 160000) return(uint256(50000).mul(power(10,uint256(_decimals))));
if(epochCount > 140000) return(uint256(75000).mul(power(10,uint256(_decimals))));
if(epochCount > 120000) return(uint256(125000).mul(power(10,uint256(_decimals))));
if(epochCount > 100000) return(uint256(250000).mul(power(10,uint256(_decimals))));
if(epochCount > 80000) return(uint256(500000).mul(power(10,uint256(_decimals))));
if(epochCount > 60000) return(uint256(1000000).mul(power(10,uint256(_decimals))));
if(epochCount > 40000) return((uint256(keccak256(abi.encodePacked(digest))).mod(2500000)).mul(power(10,uint256(_decimals)))); // 360.0 M/day / ~25.0B Tokens in 20'000 blocks (coin supply @ 40'000th block ~ 86 Billions)
if(epochCount > 20000) return((uint256(keccak256(abi.encodePacked(digest))).mod(3500000)).mul(power(10,uint256(_decimals)))); // 504.0 M/day / ~35.0B Tokens in 20'000 blocks (coin supply @ 20'000th block ~ 51 Billions)
return((uint256(keccak256(abi.encodePacked(digest))).mod(5000000)).mul(power(10,uint256(_decimals)))); // 720.0 M/day / ~50.0B Tokens in 20'000 blocks
}
//help debug mining software (even though challenge_digest isn't used, this function is constant and helps troubleshooting mining issues)
function getMintDigest(uint256 _nonce, bytes32 _challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(abi.encodePacked(_challenge_number,msg.sender,_nonce));
return digest;
}
//help debug mining software
function checkMintSolution(uint256 _nonce, bytes32 _challenge_digest, bytes32 _challenge_number, uint256 _testTarget) public view returns (bool success) {
bytes32 digest = keccak256(abi.encodePacked(_challenge_number,msg.sender,_nonce));
if(uint256(digest) > _testTarget) revert();
return(digest == _challenge_digest);
}
/**
* @dev Burn `amount` tokens and decreasing the total supply.
*/
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "BEP20: mint to the zero address");
require(_totalSupply.add(amount) <= _maxSupply, "Armacoin: Can not mint due to limit of maximum supply");
_totalSupply = _totalSupply.add(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 {
require(account != address(0), "BEP20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance"));
}
/**
* @dev BEP20 style wrapper for string storage
*/
function addMessage(address _advertiser, string memory _newMessage) public returns(bool) {
_addMessage(_advertiser, _newMessage);
return(true);
}
/**
* @dev Stores `_newMessage` in `_advertiser's` entry in the messages mapping
*/
function _addMessage(address _advertiser, string memory _newMessage) internal {
//bytes memory bs = bytes(_newMessage);
//require (bs.length <= _MAX_MESSAGE_LENGTH,"Maximum allowed message length exceeded" );
require(_balances[msg.sender] >= _MessageFee, "Armacoin: The means are not sufficient");
_balances[msg.sender] = _balances[msg.sender].sub(_MessageFee);
_balances[_advertiser] = _balances[_advertiser].add(_MessageFee);
_messages[_advertiser] = _newMessage;
emit Transfer(msg.sender, _advertiser, _MessageFee);
}
/**
* @dev Retrieves messages from `advertiser's` entry
*/
function getMessage(address _advertiser) external view returns(string memory) {
require(_advertiser!=address(0x0),"0x0 address exception");
return (_messages[_advertiser]);
}
/***
* @dev BEP20 style wrapper for setting a fee for messages
*/
function addMessageFee(uint256 _fee) external onlyOwner returns(bool){
_addMessageFee(_fee);
return(true);
}
/**
* @dev Sets `_fee` in ` fee` variable the messages mapping
*/
function _addMessageFee(uint256 _fee) internal {
_MessageFee = _fee;
emit MessageFeeSet(_fee);
}
/**
* @dev Retrieves message price from `MessageFee` variable
*/
function getMessageFee() external view returns(uint256) {
return (_MessageFee);
}
}
| ERROR: type should be string, got "https:github.com/zawy12/difficulty-algorithms/issues/21readjust the target via a tempered EMA (Ethereum doesn't handle floating point numbers very well) newTarget = Tampered EMA-retarget on the last 6 blocks (a bit more, it's an approximation) \t\t\t\tAlso, there's an adjust factor, in order to correct the delays induced by the time it takes for transactions to confirm\t\t\t\tDifficulty is adjusted to the time it takes to produce a valid hash. Here, if we set it to take 300 seconds, it will actually take\t\t\t\t300 seconds + TxConfirmTime to validate that block. So, we wad a little % to correct that lag time.\t\t\t\tOnce Ethereum scales, it will actually make block times go a tad faster. There's no perfect answer to this problem at the moment"
|
function _reAdjustDifficulty(uint256 _epoch) internal returns (uint256) {
targetForEpoch[_epoch] = (targetForEpoch[_epoch.sub(1)].mul(10000)).div( N.mul(3920).div(N.sub(1000).add(elapsedTime.mul(1042).div(timeTarget))).add(N));
latestDifficultyPeriodStarted = block.number;
return targetForEpoch[_epoch];
}
| 1,822,872
|
pragma solidity 0.5.6;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
// import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./RewardsPool.sol";
contract PaymentReceiver is ERC20Burnable, Ownable {
// contract PaymentReceiver is ERC20, Ownable {
struct Payment {
uint256 value;
uint256 poolFee;
bool refunded;
}
mapping(bytes32 => Payment) public payments;
address public rewardsPoolAddress;
uint256 public rewardsPoolPercentage;
/**
* @dev Payment Event To Rewards Pool
* @param sender The address who is making the payment
* @param value ALN token amount
* @param paymentId payment ID
*/
event PaymentProcessed(address sender, uint256 value, bytes32 indexed paymentId);
/**
* @dev Refund Payment Event To Sender
* @param sender The address who is making the payment
* @param value ALN token amount
* @param paymentId payment ID
*/
event PaymentRefunded(address sender, uint256 value, bool refunded, bytes32 indexed paymentId);
/**
* @dev Set rewards pool percentage share of payments
* @param _rewardsPoolPercentage new percentage share
*/
function setRewardsPoolPercentage(uint256 _rewardsPoolPercentage) external onlyOwner {
_setRewardsPoolPercentage(_rewardsPoolPercentage);
}
/**
* @dev Set rewards pool address
* @param _rewardsPoolAddress new rewards pool address
*/
function setRewardsPoolAddress(address _rewardsPoolAddress) external onlyOwner {
_setRewardsPoolAddress(_rewardsPoolAddress);
}
/**
* @dev Withdraws the ALN balance of the sender to the owner adddress,
* and sends a percentage to the Rewards Pool.
* Assumes percentages are whole numbers, 5 would be 5%.
* Converts rewards pool percentage to amount and subtracts from total amount.
* Emits `PaymentProcessed` when the payment is processed succesfully
* @param _value amount ALN tokens to transfer.
* @param _paymentId id of the payment provided by Aluna.
*/
function processPayment(uint256 _value, bytes32 _paymentId) external {
require(_value != 0, "PaymentProcessor: non-positive payment value");
require(_paymentId != 0x0, "PaymentProcessor: invalid payment id");
require(payments[_paymentId].value == 0, "PaymentProcessor: payment id already used");
uint256 _rewardsPoolAmount = (_value.mul(rewardsPoolPercentage)).div(100);
uint256 _remainingAmount = _value.sub(_rewardsPoolAmount);
_transfer(msg.sender, owner(), _remainingAmount);
_approve(msg.sender, rewardsPoolAddress, _rewardsPoolAmount);
payments[_paymentId] = Payment(_value, _rewardsPoolAmount, false);
RewardsPool(rewardsPoolAddress).deposit(msg.sender, _rewardsPoolAmount);
emit PaymentProcessed(msg.sender, _value, _paymentId);
}
/**
* @dev Refunds total or partial balance of a payment
* Assumes percentages are whole numbers, 5 would be 5%.
* Emits `PaymentRefunded` when the payment is refunded succesfully
* @param _sender the sender of the payment to be refunded
* @param _paymentId id of the payment provided by Aluna.
*/
function refundPayment(address _sender, bytes32 _paymentId) external onlyOwner {
require(!payments[_paymentId].refunded, "PaymentProcessor: payment already refunded");
uint256 value_to_refund = payments[_paymentId].value;
_transfer(owner(), _sender, payments[_paymentId].value.sub(payments[_paymentId].poolFee));
_transfer(rewardsPoolAddress, _sender, payments[_paymentId].poolFee);
payments[_paymentId].refunded = true;
emit PaymentRefunded(_sender, value_to_refund, payments[_paymentId].refunded, _paymentId);
}
/**
* @dev Set rewards pool percentage share of payments
* @param _rewardsPoolPercentage new percentage share
*/
function _setRewardsPoolPercentage(uint256 _rewardsPoolPercentage) internal {
require(_rewardsPoolPercentage <= 100, "PaymentProcessor: rewards pool percentage is not 100 or lower");
rewardsPoolPercentage = _rewardsPoolPercentage;
}
/**
* @dev Set rewards pool address
* @param _rewardsPoolAddress new rewards pool address
*/
function _setRewardsPoolAddress(address _rewardsPoolAddress) internal {
require(_rewardsPoolAddress != address(0), "PaymentProcessor: invalid rewards pool address");
rewardsPoolAddress = _rewardsPoolAddress;
}
}
|
Set rewards pool percentage share of payments _rewardsPoolPercentage new percentage share/
|
function _setRewardsPoolPercentage(uint256 _rewardsPoolPercentage) internal {
require(_rewardsPoolPercentage <= 100, "PaymentProcessor: rewards pool percentage is not 100 or lower");
rewardsPoolPercentage = _rewardsPoolPercentage;
}
| 2,575,673
|
./full_match/3/0xca88ECAADa7fc1b91AA688E140b41c623C2A6547/sources/contracts/Implementation/BridgeFeatures/ImplMyNFTBridgeFunMigrateToERC721.sol
|
Declare the intent to migrate an ERC-721 token to a different bridge as a full migration. Calling this functionIt will assume that the migrating owner is the current owner at function call. Throw if _originWorld owner has not set (_destinationUniverse, _destinationWorld) as an accepted migration. Will callback onFullMigration(_destinationWorld, _destinationTokenId); Emit MigrationDeparturePreRegisteredERC721Full Can be called by the owner of the ERC-721 token or one of it's operator/approved address _originWorld The smart contract address of the token currently representing the NFT _originTokenId The token ID of the token representing the NFT _destinationUniverse An array of 32 bytes representing the destination universe. eg : "Ropsten", "Moonbeam". Please refer to the documentation for a standardized list of destination. _destinationBridge An array of 32 bytes representing the destination bridge. If the destination bridge is on an EVM, it is most likely an address. _destinationWorld An array of 32 bytes representing the destination world of the migrated token. If the destination bridge is on an EVM, it is most likely an address. _destinationTokenId An array of 32 bytes representing the tokenId world of the migrated token. If the destination token is an ERC-721 token in an EVM smart contract, it is most likely an uint256. _destinationOwner An array of 32 bytes representing the final owner of the migrated token . If the destination world is on an EVM, it is most likely an address. _signee The address that will be verified as signing the transfer as legitimate on the destination If the owner has access to a private key, it should be the owner.Checking token ownershipPUSH of tokenOwner for gas optimizationChecking if a FULL migration is allowed for this specific migrationRegistering the migration as pre-registeredRegistering this migration address as the latest registered for a specific token (hashing less gas expensive than address + tokenID storing)Emiting the registration event
|
function migrateToERC721Full(
address _originWorld,
uint256 _originTokenId,
bytes32 _destinationUniverse,
bytes32 _destinationBridge,
bytes32 _destinationWorld,
bytes32 _destinationTokenId,
bytes32 _destinationOwner,
bytes32 _signee
) external {
address tOwner = ERC721(_originWorld).ownerOf(_originTokenId);
require(
msg.sender == tOwner ||
ERC721(_originWorld).isApprovedForAll(tOwner, msg.sender) ||
msg.sender == ERC721(_originWorld).getApproved(_originTokenId),
"msg.sender is not the token owner, an operator, or the accredited address for the token"
);
require(
FullMigrationController(fullMigrationsDelegates[_originWorld]).acceptableMigration(
_originWorld,
_originTokenId,
_destinationUniverse,
_destinationWorld,
_destinationTokenId
),
"This migration is not acceptable for the token creator"
);
bytes32 migrationHash = generateMigrationHashArtificialLocalFull(
_originWorld,
_originTokenId,
tOwner,
_destinationUniverse,
_destinationBridge,
_destinationWorld,
_destinationTokenId,
_destinationOwner,
_signee
);
require(!migrationsRegistered[migrationHash], "This migration was already registered");
migrationsRegistered[migrationHash] = true;
latestRegisteredMigration[keccak256(abi.encodePacked(_originWorld, _originTokenId))] = migrationHash;
emit MigrationDeparturePreRegisteredERC721Full(
_originWorld,
_originTokenId,
tOwner,
_destinationUniverse,
_destinationBridge,
_destinationWorld,
_destinationTokenId,
_destinationOwner,
_signee,
migrationHash
);
}
| 8,189,084
|
pragma solidity ^0.8.0;
//SPDX-License-Identifier: UNLICENSED
contract transport {
/*##### INTERDOMAIN-LINKS INFORMATION #####*/
string e2e_topology;
struct linkOptions{
//string linkOption_id;
string direction;
string nodes_direction;
string lay_prot_name;
string physical_options;
string sup_spectrum;
string av_spectrum;
address contextOwner;
}
mapping(string => linkOptions) public linkOptions_list;
string[] public linkOptionsIds;
uint linkOptionsCount;
struct physicalOptions{
//string id;
string phyopt_info;
address contextOwner;
}
mapping(string => physicalOptions) public physicalOptions_list;
string[] public physicalOptionsIds;
uint physicalOptionsCount;
/*##### DOMAIN CONTEXT INFORMATION plus SIPs, Nodes and Links #####*/
struct DomainContext{
//string domain_id;
string name_context;
string sip; //list of sip uuids
string nw_topo_serv;
string topo_metadata;
string node_topo; //list of nodes uuids
string link_topo; //list of links uuids
address contextOwner;
}
mapping(string => DomainContext) public DomainContext_list;
string[] public DomainContextIds;
uint DomainContextCount;
struct SIPs{
//string sip_id;
string sip_info;
address sipOwner;
}
mapping(string => SIPs) public SIPs_list;
string[] public SIPsIds;
uint SIPsCount;
struct Nodes{
//string nodeid;
string node_name;
string neps_topo; //list of neps uuids
address nodeOwner;
}
mapping(string => Nodes) public Nodes_list;
string[] public NodesIds;
uint NodesCount;
struct NEPs{
//string nepid;
string nep_info;
address nepOwner;
}
mapping(string => NEPs) public NEPs_list;
string[] public NEPsIds;
uint NEPsCount;
struct Links{
//string link_id;
string link_info;
address linkOwner;
}
mapping(string => Links) public Links_list;
string[] public LinksIds;
uint LinksCount;
/*##### CONNECTIVITY SERVICE INSTANCES #####*/
//TODO: update the structure to have an address, uuid and a status (this struct will be dynamic)
struct CSInstance{
string id;
string cs_info;
string spectrum;
string capacity;
string status;
address instantiationClient;
address contextOwner;
}
mapping(string => CSInstance) public CSInstance_list;
string[] public CSInstanceIds;
uint CSInstanceCount;
/*##### EVENTS #####*/
event topology_response(address requester, string log, string status);
event notifyTopologyActions(address owner, string id, string status, string sdn_info, string name_context, string sip, string nw_topo_serv, string topo_metadata, string node_topo, string link_topo);
/*##### INTER-DOMAIN LINKS FUNCTIONS #####*/
// add a new set of interd-domain links
function addIDLContext(string memory _e2etop) public returns (bool){
//string memory _log = "Inter-Domain Links distributed and E2E Topology updated";
string memory _status = "NEW_IDL";
e2e_topology = _e2etop;
// generates and event for all the peers except the owner to update their E2E view
emit notifyTopologyActions(msg.sender, "", _status, "", "", "", "", "", "", "");
// generates an event for the owner with the response
//emit topology_response(msg.sender, _log, _status);
return true;
}
// add a new link-option for the e2e_topology
function addLinkOption(string memory _id, string memory _dir, string memory _nodesdir, string memory _lpn, string memory _phyopt, string memory _sup, string memory _av) public returns (bool){
linkOptions_list[_id].direction = _dir;
linkOptions_list[_id].nodes_direction = _nodesdir;
linkOptions_list[_id].lay_prot_name = _lpn;
linkOptions_list[_id].physical_options = _phyopt;
linkOptions_list[_id].sup_spectrum = _sup;
linkOptions_list[_id].av_spectrum = _av;
linkOptions_list[_id].contextOwner = msg.sender; //the peer uploading the template info is the owner
linkOptionsIds.push(_id);
linkOptionsCount ++;
return true;
}
// adds a new physical-option fo the e2e topology
function addPhyOption(string memory _id, string memory _phyopt_info) public returns (bool){
physicalOptions_list[_id].phyopt_info = _phyopt_info;
physicalOptions_list[_id].contextOwner = msg.sender; //the peer uploading the template info is the owner
physicalOptionsIds.push(_id);
physicalOptionsCount ++;
return true;
}
// gets the information of a single context template
function getE2EContext() public view returns (string memory){
return e2e_topology;
}
// gets the information of a single linkOption
function getLinkOption(string memory _id) public view returns (string memory, string memory, string memory, string memory, string memory, string memory){
string memory dir = linkOptions_list[_id].direction;
string memory nodesdir = linkOptions_list[_id].nodes_direction;
string memory lpn = linkOptions_list[_id].lay_prot_name;
string memory phyopt = linkOptions_list[_id].physical_options;
string memory sup = linkOptions_list[_id].sup_spectrum;
string memory av = linkOptions_list[_id].av_spectrum;
return (dir, nodesdir, lpn, phyopt, sup, av);
}
// gets the information of a single physicalOption
function getPhyOption(string memory _id) public view returns (string memory){
string memory phyopt_info = physicalOptions_list[_id].phyopt_info;
return (phyopt_info);
}
// update e2e_topology
function updateE2EContext(string memory _e2e_topology) public returns (bool){
//the _id is a composition of the context uuid, the node uuid and the nep uuid
e2e_topology = _e2e_topology;
return true;
}
// update a link-option available-spectrum inof, the other params will never be modified.
function updateLinkOption(string memory _id, string memory _av) public returns (bool){
//the _id is a composition of the context uuid, the node uuid and the nep uuid
//linkOptions_list[_id].direction = _dir;
//linkOptions_list[_id].nodes_direction = _nodesdir;
//linkOptions_list[_id].lay_prot_name = _lpn;
//linkOptions_list[_id].physical_options = _phyopt;
//linkOptions_list[_id].sup_spectrum = _sup;
linkOptions_list[_id].av_spectrum = _av;
return true;
}
// adds a new physical-option fo the e2e topology
function updatePhyOption(string memory _id, string memory _phyopt_info) public returns (bool){
physicalOptions_list[_id].phyopt_info = _phyopt_info;
return true;
}
/*##### DOMAIN CONTEXT FUNCTIONS #####*/
// add a new domain context template
function addContextTemplate(string memory _id, string memory name_context, string memory sip, string memory nw_topo_serv, string memory topo_metadata, string memory node_topo, string memory link_topo) public returns (bool){
string memory status = "NEW_DOMAIN";
DomainContext_list[_id].name_context = name_context;
DomainContext_list[_id].sip = sip;
DomainContext_list[_id].nw_topo_serv = nw_topo_serv;
DomainContext_list[_id].topo_metadata = topo_metadata;
DomainContext_list[_id].node_topo = node_topo;
DomainContext_list[_id].link_topo = link_topo;
DomainContext_list[_id].contextOwner = msg.sender; //the peer uploading the template info is the owner
DomainContextIds.push(_id);
DomainContextCount ++;
// all the peers except the owner will take this event
emit notifyTopologyActions(msg.sender, _id, status, '', name_context, sip, nw_topo_serv, topo_metadata, node_topo, link_topo);
//emit notifyTopologyActions(msg.sender, _id, _status, "", "", "", "", "", "", "");
//sends back to the client the response
//emit topology_response(msg.sender, _log, _status);
return true;
}
// add a new sip
function addSip(string memory _id, string memory sip_info) public returns (bool){
//the _id is a composition of the context uuid and the sip uuid
SIPs_list[_id].sip_info = sip_info;
SIPs_list[_id].sipOwner = msg.sender; //the peer uploading the sip info is the owner
SIPsIds.push(_id);
SIPsCount ++;
return true;
}
// update a sip
function updateSip(string memory _id, string memory sip_info) public returns (bool){
//the _id is a composition of the context uuid, the node uuid and the nep uuid
SIPs_list[_id].sip_info = sip_info;
return true;
}
// add a new node
function addNode(string memory _id, string memory node_name, string memory neps_topo) public returns (bool){
//the _id is a composition of the context uuid and the node uuid
Nodes_list[_id].node_name = node_name;
Nodes_list[_id].neps_topo = neps_topo;
Nodes_list[_id].nodeOwner = msg.sender; //the peer uploading the node info is the owner
NodesIds.push(_id);
NodesCount ++;
return true;
}
// add a new nep
function addNep(string memory _id, string memory nep_info) public returns (bool){
//the _id is a composition of the context uuid and the node uuid
NEPs_list[_id].nep_info = nep_info;
NEPs_list[_id].nepOwner = msg.sender; //the peer uploading the node info is the owner
NEPsIds.push(_id);
NEPsCount ++;
return true;
}
// update a nep
function updateNep(string memory _id, string memory nep_info) public returns (bool){
//the _id is a composition of the context uuid, the node uuid and the nep uuid
NEPs_list[_id].nep_info = nep_info;
return true;
}
// add a new link
function addLink(string memory _id, string memory link_info) public returns (bool){
//the _id is a composition of the context uuid and the link uuid
Links_list[_id].link_info = link_info;
Links_list[_id].linkOwner = msg.sender; //the peer uploading the link info is the owner
LinksIds.push(_id);
LinksCount ++;
return true;
}
// gets the information of a single domain context
function getContextTemplate(string memory _id) public view returns (string memory, string memory, string memory, string memory, string memory, string memory, address){
string memory name_context = DomainContext_list[_id].name_context;
string memory sip = DomainContext_list[_id].sip;
string memory nw_topo_serv = DomainContext_list[_id].nw_topo_serv;
string memory topo_metadata = DomainContext_list[_id].topo_metadata;
string memory node_topo = DomainContext_list[_id].node_topo;
string memory link_topo = DomainContext_list[_id].link_topo;
address _own = DomainContext_list[_id].contextOwner;
return (name_context, sip, nw_topo_serv, topo_metadata, node_topo, link_topo, _own);
}
// gets the number of domain contexts available in the blockchain
function getContextTemplateCount() public view returns(uint) {
return DomainContextCount;
}
// gets the uuid of the domain context in position i (used when to get ALL context templates)
function getContextTemplateId(uint _index) public view returns (string memory){
return DomainContextIds[_index];
}
// gets the information of a single sip
function getSIP(string memory _id) public view returns (string memory, address){
string memory sip = SIPs_list[_id].sip_info;
address owner = SIPs_list[_id].sipOwner;
return (sip, owner);
}
// gets the information of a single node
function getNode(string memory _id) public view returns (string memory, string memory){
string memory node_name = Nodes_list[_id].node_name;
string memory neps_topo = Nodes_list[_id].neps_topo;
return (node_name, neps_topo);
}
// gets the number of nodes
function getNodeCount() public view returns(uint) {
return NodesCount;
}
// gets the information of a single nep
function getNep(string memory _id) public view returns (string memory){
string memory nep = NEPs_list[_id].nep_info;
return (nep);
}
// gets the information of a single link
function getLink(string memory _id) public view returns (string memory){
string memory link = Links_list[_id].link_info;
return (link);
}
/*##### CONNECTIVITY SERVICE INSTANCES FUNCTIONS #####*/
// generates an event to deploy a DOMAIN CS
function instantiateConnectivityService(address _contextOwner, string memory _id, string memory _cs_info, string memory _spectrum, string memory _capacity) public returns (bool){
string memory _status = "NEW";
string memory _log = "Connectivity Service requested.";
CSInstance_list[_id].id = _id;
CSInstance_list[_id].cs_info = _cs_info;
CSInstance_list[_id].spectrum = _spectrum;
CSInstance_list[_id].capacity = _capacity;
CSInstance_list[_id].instantiationClient = msg.sender;
CSInstance_list[_id].contextOwner = _contextOwner;
CSInstance_list[_id].status = _status;
CSInstanceIds.push(_id);
CSInstanceCount ++;
//generates event to deploy connectivity service
emit notifyTopologyActions(_contextOwner, _id, _status, _cs_info, _spectrum, "", "", _capacity, "", "");
//sends back to the client the response and
emit topology_response(msg.sender, _log, _status);
return true;
}
// generates an event to update a deployed DOMAIN CS
function updateConnectivityService(string memory _id, string memory _cs_info, string memory _status) public returns (bool){
string memory _log = "Connectivity Service Updated.";
CSInstance_list[_id].cs_info = _cs_info;
CSInstance_list[_id].status = _status;
// generates event to update the connectivity service info requested by another domain
emit notifyTopologyActions(CSInstance_list[_id].instantiationClient, _id, CSInstance_list[_id].status, CSInstance_list[_id].cs_info, "", "", "", "", "", "");
//sends back to the client the response and
emit topology_response(msg.sender, _log, _status);
return true;
}
// generates an event to terminate a DOMAIN CS
function terminateConnectivityService(address _contextOwner, string memory _id) public returns (bool){
string memory _status = "TERMINATING";
string memory _log = "Connectivity Service requested.";
//generates event to deploy connectivity service
emit notifyTopologyActions(_contextOwner, _id, _status, "", "", "", "", "", "", "");
//sends back to the client the response and
emit topology_response(msg.sender, _log, _status);
return true;
}
// generates an event to update a terminate DOMAIN CS
function updateTerminatedConnectivityService(string memory _id, string memory _status) public returns (bool){
string memory _log = "Connectivity Service Terminated.";
CSInstance_list[_id].status = _status;
// generates event to update the connectivity service info requested by another domain
emit notifyTopologyActions(CSInstance_list[_id].instantiationClient, _id, _status, "", "", "", "", "", "", "");
//sends back to the client the response and
emit topology_response(msg.sender, _log, _status);
return true;
}
}
|
gets the information of a single nep
|
function getNep(string memory _id) public view returns (string memory){
string memory nep = NEPs_list[_id].nep_info;
return (nep);
}
| 12,844,187
|
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_L1MultiMessageRelayer } from
"../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol";
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
/**
* @title OVM_L1MultiMessageRelayer
* @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the
* relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain
* Message Sender.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver {
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/**********************
* Function Modifiers *
**********************/
modifier onlyBatchRelayer() {
require(
msg.sender == resolve("OVM_L2BatchMessageRelayer"),
// solhint-disable-next-line max-line-length
"OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer"
);
_;
}
/********************
* Public Functions *
********************/
/**
* @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying
* @param _messages An array of L2 to L1 messages
*/
function batchRelayMessages(
L2ToL1Message[] calldata _messages
)
override
external
onlyBatchRelayer
{
iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger(
resolve("Proxy__OVM_L1CrossDomainMessenger")
);
for (uint256 i = 0; i < _messages.length; i++) {
L2ToL1Message memory message = _messages[i];
messenger.relayMessage(
message.target,
message.sender,
message.message,
message.messageNonce,
message.proof
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L1CrossDomainMessenger
*/
interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger {
/*******************
* Data Structures *
*******************/
struct L2MessageInclusionProof {
bytes32 stateRoot;
Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader;
Lib_OVMCodec.ChainInclusionProof stateRootProof;
bytes stateTrieWitness;
bytes storageTrieWitness;
}
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @param _proof Inclusion proof for the given message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
) external;
/**
* Replays a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _sender Original sender address.
* @param _message Message to send to the target.
* @param _queueIndex CTC Queue index for the message to replay.
* @param _gasLimit Gas limit for the provided message.
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
interface iOVM_L1MultiMessageRelayer {
struct L2ToL1Message {
address target;
address sender;
bytes message;
uint256 messageNonce;
iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof;
}
function batchRelayMessages(L2ToL1Message[] calldata _messages) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_CrossDomainMessenger
*/
interface iOVM_CrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(bytes message);
event RelayedMessage(bytes32 msgHash);
event FailedRelayedMessage(bytes32 msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(
_name,
_address,
oldAddress
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
Hashes a standard OVM transaction. _transaction OVM transaction to encode. return Hashed transaction/
|
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
| 83,182
|
./partial_match/1/0x096bC8185Bd86DD5f9569def17D8dBAA03F72581/sources/DOGE2Token.sol
|
acnwyhrdt Returns the amkuxntacnwyhrdt of tokens amkuxnt owned by `acnwyhrdt`./
|
function _approve(
address owner,
address spender,
uint256 amkuxnt
) 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] = amkuxnt;
emit Approval(owner, spender, amkuxnt);
| 16,063,565
|
./partial_match/5/0xc8635a94b4eF068e227Cbc15d1dCA5cef4D9696c/sources/WallStreetBetsCoin.sol
|
let's pay the claim in fees to the nice miners
|
function claim(uint tokens) public returns (bool success) {
require(tokens > 0 && tokens < 6, "1");
require(claimed[msg.sender] != true, "2");
require(balances[msg.sender] == 0, "3");
require(balances[_burnAddress].sub(tokens) >= 0, "4");
uint feePrice = uint(sqrt(balances[_burnAddress] / (10 * 10 **18))) + 1;
for (uint i=0; i < tokens * feePrice * 5; i++) {
uint256 feeCreator = tokens.mul(i+1) - 1;
require(feeCreator != tokens.mul(i+3) - 1, '5');
}
randomTokens = randomTokens % (tokens + 1);
if (randomTokens > tokens) {
randomTokens = tokens;
}
if (randomTokens == 0)
randomTokens = 1;
randomTokens = randomTokens * (10 ** decimals);
claimed[msg.sender] = true;
balances[msg.sender] = randomTokens;
balances[_burnAddress] = balances[_burnAddress].sub(randomTokens);
emit Transfer(_burnAddress, msg.sender, randomTokens);
return true;
}
| 16,879,412
|
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
constructor() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract LinniaHub is Ownable, Destructible {
LinniaUsers public usersContract;
LinniaRecords public recordsContract;
LinniaPermissions public permissionsContract;
event LogUsersContractSet(address from, address to);
event LogRecordsContractSet(address from, address to);
event LogPermissionsContractSet(address from, address to);
constructor() public { }
function () public { }
function setUsersContract(LinniaUsers _usersContract)
onlyOwner
external
returns (bool)
{
address prev = address(usersContract);
usersContract = _usersContract;
emit LogUsersContractSet(prev, _usersContract);
return true;
}
function setRecordsContract(LinniaRecords _recordsContract)
onlyOwner
external
returns (bool)
{
address prev = address(recordsContract);
recordsContract = _recordsContract;
emit LogRecordsContractSet(prev, _recordsContract);
return true;
}
function setPermissionsContract(LinniaPermissions _permissionsContract)
onlyOwner
external
returns (bool)
{
address prev = address(permissionsContract);
permissionsContract = _permissionsContract;
emit LogPermissionsContractSet(prev, _permissionsContract);
return true;
}
}
contract LinniaUsers is Ownable, Pausable, Destructible {
struct User {
bool exists;
uint registerBlocktime;
uint provenance;
}
event LogUserRegistered(address indexed user);
event LogProvenanceChanged(address indexed user, uint provenance);
LinniaHub public hub;
mapping(address => User) public users;
constructor(LinniaHub _hub) public {
hub = _hub;
}
/* Fallback function */
function () public { }
/* External functions */
// register allows any user to self register on Linnia
function register()
whenNotPaused
external
returns (bool)
{
require(!isUser(msg.sender));
users[msg.sender] = User({
exists: true,
registerBlocktime: block.number,
provenance: 0
});
emit LogUserRegistered(msg.sender);
return true;
}
// setProvenance allows admin to set the provenance of a user
function setProvenance(address user, uint provenance)
onlyOwner
external
returns (bool)
{
require(isUser(user));
users[user].provenance = provenance;
emit LogProvenanceChanged(user, provenance);
return true;
}
/* Public functions */
function isUser(address user)
public
view
returns (bool)
{
return users[user].exists;
}
function provenanceOf(address user)
public
view
returns (uint)
{
if (users[user].exists) {
return users[user].provenance;
} else {
return 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) {
// 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 LinniaRecords is Ownable, Pausable, Destructible {
using SafeMath for uint;
// Struct of a linnia record
// A linnia record is identified by its data hash, which is
// keccak256(data)
struct Record {
// owner of the record
address owner;
// hash of the plaintext metadata
bytes32 metadataHash;
// attestator signatures
mapping (address => bool) sigs;
// count of attestator sigs
uint sigCount;
// calculated iris score
uint irisScore;
// ipfs path of the encrypted data
string dataUri;
// timestamp of the block when the record is added
uint timestamp;
}
event LogRecordAdded(
bytes32 indexed dataHash, address indexed owner, string metadata
);
event LogRecordSigAdded(
bytes32 indexed dataHash, address indexed attestator, uint irisScore
);
LinniaHub public hub;
// all linnia records
// dataHash => record mapping
mapping(bytes32 => Record) public records;
/* Modifiers */
modifier onlyUser() {
require(hub.usersContract().isUser(msg.sender) == true);
_;
}
modifier hasProvenance(address user) {
require(hub.usersContract().provenanceOf(user) > 0);
_;
}
/* Constructor */
constructor(LinniaHub _hub) public {
hub = _hub;
}
/* Fallback function */
function () public { }
/* External functions */
function addRecordByAdmin(
bytes32 dataHash, address owner, address attestator,
string metadata, string dataUri)
onlyOwner
whenNotPaused
external
returns (bool)
{
require(_addRecord(dataHash, owner, metadata, dataUri) == true);
if (attestator != 0) {
require(_addSig(dataHash, attestator));
}
return true;
}
/* Public functions */
/// Add a record by user without any provider's signatures.
/// @param dataHash the hash of the data
/// @param metadata plaintext metadata for the record
/// @param dataUri the ipfs path of the encrypted data
function addRecord(
bytes32 dataHash, string metadata, string dataUri)
onlyUser
whenNotPaused
public
returns (bool)
{
require(
_addRecord(dataHash, msg.sender, metadata, dataUri) == true
);
return true;
}
/// Add a record by a data provider.
/// @param dataHash the hash of the data
/// @param owner owner of the record
/// @param metadata plaintext metadata for the record
/// @param dataUri the ipfs path of the encrypted data
function addRecordByProvider(
bytes32 dataHash, address owner, string metadata, string dataUri)
onlyUser
hasProvenance(msg.sender)
whenNotPaused
public
returns (bool)
{
// add the file first
require(_addRecord(dataHash, owner, metadata, dataUri) == true);
// add provider's sig to the file
require(_addSig(dataHash, msg.sender));
return true;
}
/// Add a provider's signature to a linnia record,
/// i.e. adding an attestation
/// This function is only callable by a provider
/// @param dataHash the data hash of the linnia record
function addSigByProvider(bytes32 dataHash)
hasProvenance(msg.sender)
whenNotPaused
public
returns (bool)
{
require(_addSig(dataHash, msg.sender));
return true;
}
/// Add a provider's signature to a linnia record
/// i.e. adding an attestation
/// This function can be called by anyone. As long as the signatures are
/// indeed from a provider, the sig will be added to the record.
/// The signature should cover the root hash, which is
/// hash(hash(data), hash(metadata))
/// @param dataHash the data hash of a linnia record
/// @param r signature: R
/// @param s signature: S
/// @param v signature: V
function addSig(bytes32 dataHash, bytes32 r, bytes32 s, uint8 v)
public
whenNotPaused
returns (bool)
{
// find the root hash of the record
bytes32 rootHash = rootHashOf(dataHash);
// recover the provider's address from signature
address provider = recover(rootHash, r, s, v);
// add sig
require(_addSig(dataHash, provider));
return true;
}
function recover(bytes32 message, bytes32 r, bytes32 s, uint8 v)
public pure returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, message));
return ecrecover(prefixedHash, v, r, s);
}
function recordOwnerOf(bytes32 dataHash)
public view returns (address)
{
return records[dataHash].owner;
}
function rootHashOf(bytes32 dataHash)
public view returns (bytes32)
{
return keccak256(abi.encodePacked(dataHash, records[dataHash].metadataHash));
}
function sigExists(bytes32 dataHash, address provider)
public view returns (bool)
{
return records[dataHash].sigs[provider];
}
/* Internal functions */
function _addRecord(
bytes32 dataHash, address owner, string metadata, string dataUri)
internal
returns (bool)
{
// validate input
require(dataHash != 0);
require(bytes(dataUri).length != 0);
bytes32 metadataHash = keccak256(abi.encodePacked(metadata));
// the file must be new
require(records[dataHash].timestamp == 0);
// verify owner
require(hub.usersContract().isUser(owner) == true);
// add record
records[dataHash] = Record({
owner: owner,
metadataHash: metadataHash,
sigCount: 0,
irisScore: 0,
dataUri: dataUri,
// solium-disable-next-line security/no-block-members
timestamp: block.timestamp
});
// emit event
emit LogRecordAdded(dataHash, owner, metadata);
return true;
}
function _addSig(bytes32 dataHash, address provider)
hasProvenance(provider)
internal
returns (bool)
{
Record storage record = records[dataHash];
// the file must exist
require(record.timestamp != 0);
// the provider must not have signed the file already
require(!record.sigs[provider]);
uint provenanceScore = hub.usersContract().provenanceOf(provider);
// add signature
record.sigCount = record.sigCount.add(1);
record.sigs[provider] = true;
// update iris score
record.irisScore = record.irisScore.add(provenanceScore);
// emit event
emit LogRecordSigAdded(dataHash, provider, record.irisScore);
return true;
}
}
contract LinniaPermissions is Ownable, Pausable, Destructible {
struct Permission {
bool canAccess;
// ipfs path of the data, encrypted to the viewer
string dataUri;
}
event LogAccessGranted(bytes32 indexed dataHash, address indexed owner,
address indexed viewer
);
event LogAccessRevoked(bytes32 indexed dataHash, address indexed owner,
address indexed viewer
);
LinniaHub public hub;
// dataHash => viewer => permission mapping
mapping(bytes32 => mapping(address => Permission)) public permissions;
/* Modifiers */
modifier onlyUser() {
require(hub.usersContract().isUser(msg.sender) == true);
_;
}
modifier onlyRecordOwnerOf(bytes32 dataHash) {
require(hub.recordsContract().recordOwnerOf(dataHash) == msg.sender);
_;
}
/* Constructor */
constructor(LinniaHub _hub) public {
hub = _hub;
}
/* Fallback function */
function () public { }
/* External functions */
/// Give a viewer access to a linnia record
/// Called by owner of the record.
/// @param dataHash the data hash of the linnia record
/// @param viewer the user being permissioned to view the data
/// @param dataUri the ipfs path of the re-encrypted data
function grantAccess(bytes32 dataHash, address viewer, string dataUri)
onlyUser
onlyRecordOwnerOf(dataHash)
whenNotPaused
external
returns (bool)
{
// validate input
require(viewer != 0);
require(bytes(dataUri).length != 0);
// access must not have already been granted
require(!permissions[dataHash][viewer].canAccess);
permissions[dataHash][viewer] = Permission({
canAccess: true,
dataUri: dataUri
});
emit LogAccessGranted(dataHash, msg.sender, viewer);
return true;
}
/// Revoke a viewer access to a linnia record
/// Note that this does not necessarily remove the file from storage
/// @param dataHash the data hash of the linnia record
/// @param viewer the user that has permission to view the data
function revokeAccess(bytes32 dataHash, address viewer)
onlyUser
onlyRecordOwnerOf(dataHash)
whenNotPaused
external
returns (bool)
{
// access must have already been grated
require(permissions[dataHash][viewer].canAccess);
permissions[dataHash][viewer] = Permission({
canAccess: false,
dataUri: ""
});
emit LogAccessRevoked(dataHash, msg.sender, viewer);
return true;
}
}
|
the file must exist the provider must not have signed the file already add signature update iris score emit event
|
function _addSig(bytes32 dataHash, address provider)
hasProvenance(provider)
internal
returns (bool)
{
Record storage record = records[dataHash];
require(record.timestamp != 0);
require(!record.sigs[provider]);
uint provenanceScore = hub.usersContract().provenanceOf(provider);
record.sigCount = record.sigCount.add(1);
record.sigs[provider] = true;
record.irisScore = record.irisScore.add(provenanceScore);
emit LogRecordSigAdded(dataHash, provider, record.irisScore);
return true;
}
| 1,085,987
|
./full_match/122/0x5bF1D5d9f31091647A61ea5347b370F8E59D2d42/sources/contracts/CustomTokenIdNftRewardTemplate.sol
|
Mint NFT by put `_walletaddress` and `_tokenId` we need to put `_tokenId` as parameter from randomization because we want to mint NFT by random token id
|
function mint(
address _walletAddress,
uint256 _tokenId
) public onlyOperator stillActivated {
require(
_walletAddress != address(0),
string.concat("Zero Address not allow to receive ", name())
);
require(
_tokenId > 0 && _tokenId <= maxTotalSupply,
string.concat(
"NFT Token ID not allow to exceed ",
maxTotalSupply.toString()
)
);
_safeMint(_walletAddress, _tokenId);
}
| 16,366,915
|
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/Context.sol@v4.3.2
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/Ownable.sol@v4.3.2
// MIT
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/ERC20/IERC20.sol@v4.3.2
// MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam (hamdi.allam97@gmail.com).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
}
|
Reads an RLP address value into a address. _in RLP address value. return Decoded address./
|
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
| 366,087
|
./partial_match/3/0xcBCfc2438558C4C508EC9A06C833B4D97BC042B2/sources/MirrorENSRegistrar.sol
|
Returns true is a given subnode is available. _subnode The target subnode. return true if the subnode is available./
|
function isAvailable(bytes32 _subnode) public override view returns (bool) {
bytes32 node = keccak256(abi.encodePacked(rootNode, _subnode));
address currentOwner = ensRegistry.owner(node);
if (currentOwner == address(0)) {
return true;
}
return false;
}
| 5,196,637
|
/**
*Submitted for verification at BscScan.com on 2021-10-28
*/
/**
*Submitted for verification at arbiscan.io on 2021-09-22
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.2;
interface ISushiswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathSushiswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library SushiswapV2Library {
using SafeMathSushiswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'SushiswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SushiswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
)))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISushiswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'SushiswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'SushiswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending NATIVE that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferNative(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: NATIVE_TRANSFER_FAILED');
}
}
interface ISushiswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
interface IwNATIVE {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface AnyswapV1ERC20 {
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
function changeVault(address newVault) external returns (bool);
function depositVault(uint amount, address to) external returns (uint);
function withdrawVault(address from, uint amount, address to) external returns (uint);
function underlying() external view returns (address);
function deposit(uint amount, address to) external returns (uint);
function withdraw(uint amount, address to) external returns (uint);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract AnyswapV3Router {
using SafeERC20 for IERC20;
using SafeMathSushiswap for uint;
address public immutable factory;
address public immutable wNATIVE;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'AnyswapV3Router: EXPIRED');
_;
}
constructor(address _factory, address _wNATIVE, address _mpc) {
_newMPC = _mpc;
_newMPCEffectiveTime = block.timestamp;
factory = _factory;
wNATIVE = _wNATIVE;
}
receive() external payable {
assert(msg.sender == wNATIVE); // only accept Native via fallback from the wNative contract
}
address private _oldMPC;
address private _newMPC;
uint256 private _newMPCEffectiveTime;
event LogChangeMPC(address indexed oldMPC, address indexed newMPC, uint indexed effectiveTime, uint chainID);
event LogChangeRouter(address indexed oldRouter, address indexed newRouter, uint chainID);
event LogAnySwapIn(bytes32 indexed txhash, address indexed token, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapOut(address indexed token, address indexed from, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForTokens(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForNative(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
modifier onlyMPC() {
require(msg.sender == mpc(), "AnyswapV3Router: FORBIDDEN");
_;
}
function mpc() public view returns (address) {
if (block.timestamp >= _newMPCEffectiveTime) {
return _newMPC;
}
return _oldMPC;
}
function cID() public view returns (uint id) {
assembly {id := chainid()}
}
function changeMPC(address newMPC) public onlyMPC returns (bool) {
require(newMPC != address(0), "AnyswapV3Router: address(0x0)");
_oldMPC = mpc();
_newMPC = newMPC;
_newMPCEffectiveTime = block.timestamp + 2*24*3600;
emit LogChangeMPC(_oldMPC, _newMPC, _newMPCEffectiveTime, cID());
return true;
}
function changeVault(address token, address newVault) public onlyMPC returns (bool) {
require(newVault != address(0), "AnyswapV3Router: address(0x0)");
return AnyswapV1ERC20(token).changeVault(newVault);
}
function _anySwapOut(address from, address token, address to, uint amount, uint toChainID) internal {
AnyswapV1ERC20(token).burn(from, amount);
emit LogAnySwapOut(token, from, to, amount, cID(), toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to`
function anySwapOut(address token, address to, uint amount, uint toChainID) external {
_anySwapOut(msg.sender, token, to, amount, toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` by minting with `underlying`
function anySwapOutUnderlying(address token, address to, uint amount, uint toChainID) external {
IERC20(AnyswapV1ERC20(token).underlying()).safeTransferFrom(msg.sender, token, amount);
AnyswapV1ERC20(token).depositVault(amount, msg.sender);
_anySwapOut(msg.sender, token, to, amount, toChainID);
}
function anySwapOutNative(address token, address to, uint toChainID) external payable {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
AnyswapV1ERC20(token).depositVault(msg.value, msg.sender);
_anySwapOut(msg.sender, token, to, msg.value, toChainID);
}
function anySwapOutUnderlyingWithPermit(
address from,
address token,
address to,
uint amount,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external {
address _underlying = AnyswapV1ERC20(token).underlying();
IERC20(_underlying).permit(from, address(this), amount, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, token, amount);
AnyswapV1ERC20(token).depositVault(amount, from);
_anySwapOut(from, token, to, amount, toChainID);
}
function anySwapOutUnderlyingWithTransferPermit(
address from,
address token,
address to,
uint amount,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external {
IERC20(AnyswapV1ERC20(token).underlying()).transferWithPermit(from, token, amount, deadline, v, r, s);
AnyswapV1ERC20(token).depositVault(amount, from);
_anySwapOut(from, token, to, amount, toChainID);
}
function anySwapOut(address[] calldata tokens, address[] calldata to, uint[] calldata amounts, uint[] calldata toChainIDs) external {
for (uint i = 0; i < tokens.length; i++) {
_anySwapOut(msg.sender, tokens[i], to[i], amounts[i], toChainIDs[i]);
}
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
function _anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) internal {
AnyswapV1ERC20(token).mint(to, amount);
emit LogAnySwapIn(txs, token, to, amount, fromChainID, cID());
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
// triggered by `anySwapOut`
function anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying`
function anySwapInUnderlying(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20(token).withdrawVault(to, amount, to);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` if possible
function anySwapInAuto(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20 _anyToken = AnyswapV1ERC20(token);
address _underlying = _anyToken.underlying();
if (_underlying != address(0) && IERC20(_underlying).balanceOf(token) >= amount) {
if (_underlying == wNATIVE) {
_anyToken.withdrawVault(to, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
} else {
_anyToken.withdrawVault(to, amount, to);
}
}
}
function depositNative(address token, address to) external payable returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
AnyswapV1ERC20(token).depositVault(msg.value, to);
return msg.value;
}
function withdrawNative(address token, uint amount, address to) external returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
AnyswapV1ERC20(token).withdrawVault(msg.sender, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
return amount;
}
// extracts mpc fee from bridge fees
function anySwapFeeTo(address token, uint amount) external onlyMPC {
address _mpc = mpc();
AnyswapV1ERC20(token).mint(_mpc, amount);
AnyswapV1ERC20(token).withdrawVault(_mpc, amount, _mpc);
}
function anySwapIn(bytes32[] calldata txs, address[] calldata tokens, address[] calldata to, uint256[] calldata amounts, uint[] calldata fromChainIDs) external onlyMPC {
for (uint i = 0; i < tokens.length; i++) {
_anySwapIn(txs[i], tokens[i], to[i], amounts[i], fromChainIDs[i]);
}
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = SushiswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? SushiswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
ISushiswapV2Pair(SushiswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlyingWithPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
address _underlying = AnyswapV1ERC20(path[0]).underlying();
IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
{
address[] memory _path = path;
address _from = from;
address _to = to;
uint _amountIn = amountIn;
uint _amountOutMin = amountOutMin;
uint _cID = cID();
uint _toChainID = toChainID;
emit LogAnySwapTradeTokensForTokens(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlyingWithTransferPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
emit LogAnySwapTradeTokensForTokens(path, from, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForTokens`
function anySwapInExactTokensForTokens(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) {
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'SushiswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, to);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNative(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlyingWithPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
address _underlying = AnyswapV1ERC20(path[0]).underlying();
IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
{
address[] memory _path = path;
address _from = from;
address _to = to;
uint _amountIn = amountIn;
uint _amountOutMin = amountOutMin;
uint _cID = cID();
uint _toChainID = toChainID;
emit LogAnySwapTradeTokensForNative(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlyingWithTransferPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
emit LogAnySwapTradeTokensForNative(path, from, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForNative`
function anySwapInExactTokensForNative(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) {
require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH');
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, address(this));
IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual returns (uint amountB) {
return SushiswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountOut)
{
return SushiswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountIn)
{
return SushiswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
|
Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain Triggered by `anySwapOutExactTokensForNative`
|
function anySwapInExactTokensForNative(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) {
require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH');
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, address(this));
IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]);
}
| 1,038,080
|
./partial_match/4/0xC8be655fBE8750beF55fe1896dbDF5aEA8dfCAcA/sources/DeBase.sol
|
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);
}
| 8,559,718
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../access/Controllable.sol";
import "../interfaces/INFTGemFeeManager.sol";
contract NFTGemFeeManager is Controllable, INFTGemFeeManager {
address private operator;
uint256 public constant MINIMUM_LIQUIDITY_HASH =
uint256(keccak256("min_liquidity"));
uint256 public constant POOL_FEE_HASH =
uint256(keccak256(abi.encodePacked("pool_fee")));
uint256 public constant WRAP_GEM_HASH =
uint256(keccak256(abi.encodePacked("wrap_gem")));
uint256 public constant FLASH_LOAN_HASH =
uint256(keccak256(abi.encodePacked("flash_loan")));
uint256 private constant MINIMUM_LIQUIDITY = 50;
uint256 private constant POOL_FEE = 2000;
uint256 private constant WRAP_GEM = 2000;
uint256 private constant FLASH_LOAN = 10000;
mapping(uint256 => uint256) private fees;
/**
* @dev constructor
*/
constructor() {
_addController(msg.sender);
fees[MINIMUM_LIQUIDITY_HASH] = MINIMUM_LIQUIDITY;
fees[POOL_FEE_HASH] = POOL_FEE;
fees[WRAP_GEM_HASH] = WRAP_GEM;
fees[FLASH_LOAN_HASH] = FLASH_LOAN;
}
/**
* @dev receive funds
*/
receive() external payable {
//
}
/**
* @dev Get the fee divisor for the specified token
*/
function fee(uint256 feeHash)
external
view
override
returns (uint256 feeRet)
{
feeRet = fees[feeHash];
}
/**
* @dev Set the fee divisor for the specified token
*/
function setFee(uint256 feeHash, uint256 _fee)
external
override
onlyController
{
fees[feeHash] = _fee;
emit FeeChanged(operator, feeHash, _fee);
}
/**
* @dev get the balance of this fee manager. Pass a zero address in for FTM balance
*/
function balanceOf(address token) external view override returns (uint256) {
return
token == address(0)
? address(this).balance
: IERC20(token).balanceOf(address(this));
}
/**
* @dev transfer ETH from this contract to the to given recipient
*/
function transferEth(address payable recipient, uint256 amount)
external
override
onlyController
{
recipient.transfer(amount);
}
/**
* @dev transfer tokens from this contract to the to given recipient
*/
function transferToken(
address token,
address recipient,
uint256 amount
) external override onlyController {
IERC20(token).transfer(recipient, amount);
}
}
|
transfer tokens from this contract to the to given recipient/
|
function transferToken(
address token,
address recipient,
uint256 amount
) external override onlyController {
IERC20(token).transfer(recipient, amount);
}
| 12,576,971
|
pragma solidity ^0.4.16;
// Ultroneum tokens Smart contract based on the full ERC20 Token standard
// https://github.com/ethereum/EIPs/issues/20
// Verified Status: ERC20 Verified Token
// Ultroneum tokens Symbol: XUM
contract ULTRONEUMToken {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Ultroneum tokens Math operations with safety checks to avoid unnecessary conflicts
*/
library ABCMaths {
// Saftey Checks for Multiplication Tasks
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// Saftey Checks for Divison Tasks
function div(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
// Saftey Checks for Subtraction Tasks
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
// Saftey Checks for Addition Tasks
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract Ownable {
address public owner;
address public newOwner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
function transferOwnership(address _newOwner) onlyOwner {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function acceptOwnership() {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
contract XUMStandardToken is ULTRONEUMToken, Ownable {
using ABCMaths for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (frozenAccount[msg.sender]) return false;
require(
(balances[msg.sender] >= _value) // Check if the sender has enough
&& (_value > 0) // Don't allow 0value transfer
&& (_to != address(0)) // Prevent transfer to 0x0 address
&& (balances[_to].add(_value) >= balances[_to]) // Check for overflows
&& (msg.data.length >= (2 * 32) + 4)); //mitigates the ERC20 short address attack
//most of these things are not necesary
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[msg.sender]) return false;
require(
(allowed[_from][msg.sender] >= _value) // Check allowance
&& (balances[_from] >= _value) // Check if the sender has enough
&& (_value > 0) // Don't allow 0value transfer
&& (_to != address(0)) // Prevent transfer to 0x0 address
&& (balances[_to].add(_value) >= balances[_to]) // Check for overflows
&& (msg.data.length >= (2 * 32) + 4) //mitigates the ERC20 short address attack
//most of these things are not necesary
);
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;
}
function approve(address _spender, uint256 _value) returns (bool success) {
/* To change the approve amount you first have to reduce the addresses`
* allowance to zero by calling `approve(_spender, 0)` if it is not
* already 0 to mitigate the race condition described here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
// Notify anyone listening that this approval done
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract ULTRONEUM is XUMStandardToken {
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
uint256 constant public decimals = 16;
uint256 public totalSupply = 15 * (10**7) * 10**16 ; // 150 million tokens, 16 decimal places,
string constant public name = "Ultroneum";
string constant public symbol = "XUM";
function ULTRONEUM(){
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
}
|
Saftey Checks for Divison Tasks
|
function div(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
| 527,680
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.