file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
//Address: 0xfd9683e9f2c62e08b6bf68123e18e527efa8fbbc
//Contract name: CtdToken
//Balance: 1.0000000001 Ether
//Verification Date: 10/19/2017
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity 0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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() {
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 PausableOnce
* @dev The PausableOnce contract provides an option for the "pauseMaster"
* to pause once the transactions for two weeks.
*
*/
contract PausableOnce is Ownable {
/** Address that can start the pause */
address public pauseMaster;
uint constant internal PAUSE_DURATION = 14 days;
uint64 public pauseEnd = 0;
event Paused();
/**
* @dev Set the pauseMaster (callable by the owner only).
* @param _pauseMaster The address of the pauseMaster
*/
function setPauseMaster(address _pauseMaster) onlyOwner external returns (bool success) {
require(_pauseMaster != address(0));
pauseMaster = _pauseMaster;
return true;
}
/**
* @dev Start the pause (by the pauseMaster, ONCE only).
*/
function pause() onlyPauseMaster external returns (bool success) {
require(pauseEnd == 0);
pauseEnd = uint64(now + PAUSE_DURATION);
Paused();
return true;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(now > pauseEnd);
_;
}
/**
* @dev Throws if called by any account other than the pauseMaster.
*/
modifier onlyPauseMaster() {
require(msg.sender == pauseMaster);
_;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Upgrade agent interface
*/
contract InterfaceUpgradeAgent {
uint32 public revision;
uint256 public originalSupply;
/**
* @dev Reissue the tokens onto the new contract revision.
* @param holder Holder (owner) of the tokens
* @param tokenQty How many tokens to be issued
*/
function upgradeFrom(address holder, uint256 tokenQty) public;
}
/**
* @title UpgradableToken
* @dev The UpgradableToken contract provides an option of upgrading the tokens to a new revision.
* The "upgradeMaster" may propose the upgrade. Token holders can opt-in amount of tokens to upgrade.
*/
contract UpgradableToken is StandardToken, Ownable {
using SafeMath for uint256;
uint32 public REVISION;
/** Address that can set the upgrade agent thus enabling the upgrade. */
address public upgradeMaster = address(0);
/** Address of the contract that issues the new revision tokens. */
address public upgradeAgent = address(0);
/** How many tokens are upgraded. */
uint256 public totalUpgraded;
event Upgrade(address indexed _from, uint256 _value);
event UpgradeEnabled(address agent);
/**
* @dev Set the upgrade master.
* parameter _upgradeMaster Upgrade master
*/
function setUpgradeMaster(address _upgradeMaster) onlyOwner external {
require(_upgradeMaster != address(0));
upgradeMaster = _upgradeMaster;
}
/**
* @dev Set the upgrade agent (once only) thus enabling the upgrade.
* @param _upgradeAgent Upgrade agent contract address
* @param _revision Unique ID that agent contract must return on ".revision()"
*/
function setUpgradeAgent(address _upgradeAgent, uint32 _revision)
onlyUpgradeMaster whenUpgradeDisabled external
{
require((_upgradeAgent != address(0)) && (_revision != 0));
InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(_upgradeAgent);
require(agent.revision() == _revision);
require(agent.originalSupply() == totalSupply);
upgradeAgent = _upgradeAgent;
UpgradeEnabled(_upgradeAgent);
}
/**
* @dev Upgrade tokens to the new revision.
* @param value How many tokens to be upgraded
*/
function upgrade(uint256 value) whenUpgradeEnabled external {
require(value > 0);
uint256 balance = balances[msg.sender];
require(balance > 0);
// Take tokens out from the old contract
balances[msg.sender] = balance.sub(value);
totalSupply = totalSupply.sub(value);
totalUpgraded = totalUpgraded.add(value);
// Issue the new revision tokens
InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(upgradeAgent);
agent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, value);
}
/**
* @dev Modifier to make a function callable only when the upgrade is enabled.
*/
modifier whenUpgradeEnabled() {
require(upgradeAgent != address(0));
_;
}
/**
* @dev Modifier to make a function callable only when the upgrade is impossible.
*/
modifier whenUpgradeDisabled() {
require(upgradeAgent == address(0));
_;
}
/**
* @dev Throws if called by any account other than the upgradeMaster.
*/
modifier onlyUpgradeMaster() {
require(msg.sender == upgradeMaster);
_;
}
}
/**
* @title Withdrawable
* @dev The Withdrawable contract provides a mechanism of withdrawal(s).
* "Withdrawals" are permissions for specified addresses to pull (withdraw) payments from the contract balance.
*/
contract Withdrawable {
mapping (address => uint) pendingWithdrawals;
/*
* @dev Logged upon a granted allowance to the specified drawer on withdrawal.
* @param drawer The address of the drawer.
* @param weiAmount The value in Wei which may be withdrawn.
*/
event Withdrawal(address indexed drawer, uint256 weiAmount);
/*
* @dev Logged upon a withdrawn value.
* @param drawer The address of the drawer.
* @param weiAmount The value in Wei which has been withdrawn.
*/
event Withdrawn(address indexed drawer, uint256 weiAmount);
/*
* @dev Allow the specified drawer to withdraw the specified value from the contract balance.
* @param drawer The address of the drawer.
* @param weiAmount The value in Wei allowed to withdraw.
* @return success
*/
function setWithdrawal(address drawer, uint256 weiAmount) internal returns (bool success) {
if ((drawer != address(0)) && (weiAmount > 0)) {
uint256 oldBalance = pendingWithdrawals[drawer];
uint256 newBalance = oldBalance + weiAmount;
if (newBalance > oldBalance) {
pendingWithdrawals[drawer] = newBalance;
Withdrawal(drawer, weiAmount);
return true;
}
}
return false;
}
/*
* @dev Withdraw the allowed value from the contract balance.
* @return success
*/
function withdraw() public returns (bool success) {
uint256 weiAmount = pendingWithdrawals[msg.sender];
require(weiAmount > 0);
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(weiAmount);
Withdrawn(msg.sender, weiAmount);
return true;
}
}
/**
* @title Cointed Token
* @dev Cointed Token (CTD) and Token Sale (ICO).
*/
contract CtdToken is UpgradableToken, PausableOnce, Withdrawable {
using SafeMath for uint256;
string public constant name = "Cointed Token";
string public constant symbol = "CTD";
/** Number of "Atom" in 1 CTD (1 CTD = 1x10^decimals Atom) */
uint8 public constant decimals = 18;
/** Holder of bounty tokens */
address public bounty;
/** Limit (in Atom) issued, inclusive owner's and bounty shares */
uint256 constant internal TOTAL_LIMIT = 650000000 * (10 ** uint256(decimals));
/** Limit (in Atom) for Pre-ICO Phases A, incl. owner's and bounty shares */
uint256 constant internal PRE_ICO_LIMIT = 130000000 * (10 ** uint256(decimals));
/**
* ICO Phases.
*
* - PreStart: tokens are not yet sold/issued
* - PreIcoA: new tokens sold/issued at the premium price
* - PreIcoB: new tokens sold/issued at the discounted price
* - MainIco new tokens sold/issued at the regular price
* - AfterIco: new tokens can not be not be sold/issued any longer
*/
enum Phases {PreStart, PreIcoA, PreIcoB, MainIco, AfterIco}
uint64 constant internal PRE_ICO_DURATION = 30 days;
uint64 constant internal ICO_DURATION = 82 days;
uint64 constant internal RETURN_WEI_PAUSE = 30 days;
// Main ICO rate in CTD(s) per 1 ETH:
uint256 constant internal TO_SENDER_RATE = 1000;
uint256 constant internal TO_OWNER_RATE = 263;
uint256 constant internal TO_BOUNTY_RATE = 52;
uint256 constant internal TOTAL_RATE = TO_SENDER_RATE + TO_OWNER_RATE + TO_BOUNTY_RATE;
// Pre-ICO Phase A rate
uint256 constant internal TO_SENDER_RATE_A = 1150;
uint256 constant internal TO_OWNER_RATE_A = 304;
uint256 constant internal TO_BOUNTY_RATE_A = 61;
uint256 constant internal TOTAL_RATE_A = TO_SENDER_RATE_A + TO_OWNER_RATE_A + TO_BOUNTY_RATE_A;
// Pre-ICO Phase B rate
uint256 constant internal TO_SENDER_RATE_B = 1100;
uint256 constant internal TO_OWNER_RATE_B = 292;
uint256 constant internal TO_BOUNTY_RATE_B = 58;
uint256 constant internal TOTAL_RATE_B = TO_SENDER_RATE_B + TO_OWNER_RATE_B + TO_BOUNTY_RATE_B;
// Award in Wei(s) to a successful initiator of a Phase shift
uint256 constant internal PRE_OPENING_AWARD = 100 * (10 ** uint256(15));
uint256 constant internal ICO_OPENING_AWARD = 200 * (10 ** uint256(15));
uint256 constant internal ICO_CLOSING_AWARD = 500 * (10 ** uint256(15));
struct Rates {
uint256 toSender;
uint256 toOwner;
uint256 toBounty;
uint256 total;
}
event NewTokens(uint256 amount);
event NewFunds(address funder, uint256 value);
event NewPhase(Phases phase);
// current Phase
Phases public phase = Phases.PreStart;
// Timestamps limiting duration of Phases, in seconds since Unix epoch.
uint64 public preIcoOpeningTime; // when Pre-ICO Phase A starts
uint64 public icoOpeningTime; // when Main ICO starts (if not sold out before)
uint64 public closingTime; // by when the ICO campaign finishes in any way
uint64 public returnAllowedTime; // when owner may withdraw Eth from contract, if any
uint256 public totalProceeds;
/*
* @dev constructor
* @param _preIcoOpeningTime Timestamp when the Pre-ICO (Phase A) shall start.
* msg.value MUST be at least the sum of awards.
*/
function CtdToken(uint64 _preIcoOpeningTime) payable {
require(_preIcoOpeningTime > now);
preIcoOpeningTime = _preIcoOpeningTime;
icoOpeningTime = preIcoOpeningTime + PRE_ICO_DURATION;
closingTime = icoOpeningTime + ICO_DURATION;
}
/*
* @dev Fallback function delegates the request to create().
*/
function () payable external {
create();
}
/**
* @dev Set the address of the holder of bounty tokens.
* @param _bounty The address of the bounty token holder.
* @return success/failure
*/
function setBounty(address _bounty) onlyOwner external returns (bool success) {
require(_bounty != address(0));
bounty = _bounty;
return true;
}
/**
* @dev Mint tokens and add them to the balance of the message.sender.
* Additional tokens are minted and added to the owner and the bounty balances.
* @return success/failure
*/
function create() payable whenNotClosed whenNotPaused public returns (bool success) {
require(msg.value > 0);
require(now >= preIcoOpeningTime);
Phases oldPhase = phase;
uint256 weiToParticipate = msg.value;
uint256 overpaidWei;
adjustPhaseBasedOnTime();
if (phase != Phases.AfterIco) {
Rates memory rates = getRates();
uint256 newTokens = weiToParticipate.mul(rates.total);
uint256 requestedSupply = totalSupply.add(newTokens);
uint256 oversoldTokens = computeOversoldAndAdjustPhase(requestedSupply);
overpaidWei = (oversoldTokens > 0) ? oversoldTokens.div(rates.total) : 0;
if (overpaidWei > 0) {
weiToParticipate = msg.value.sub(overpaidWei);
newTokens = weiToParticipate.mul(rates.total);
requestedSupply = totalSupply.add(newTokens);
}
// "emission" of new tokens
totalSupply = requestedSupply;
balances[msg.sender] = balances[msg.sender].add(weiToParticipate.mul(rates.toSender));
balances[owner] = balances[owner].add(weiToParticipate.mul(rates.toOwner));
balances[bounty] = balances[bounty].add(weiToParticipate.mul(rates.toBounty));
// ETH transfers
totalProceeds = totalProceeds.add(weiToParticipate);
owner.transfer(weiToParticipate);
if (overpaidWei > 0) {
setWithdrawal(msg.sender, overpaidWei);
}
// Logging
NewTokens(newTokens);
NewFunds(msg.sender, weiToParticipate);
} else {
setWithdrawal(msg.sender, msg.value);
}
if (phase != oldPhase) {
logShiftAndBookAward();
}
return true;
}
/**
* @dev Send the value (ethers) that the contract holds to the owner address.
*/
function returnWei() onlyOwner whenClosed afterWithdrawPause external {
owner.transfer(this.balance);
}
function adjustPhaseBasedOnTime() internal {
if (now >= closingTime) {
if (phase != Phases.AfterIco) {
phase = Phases.AfterIco;
}
} else if (now >= icoOpeningTime) {
if (phase != Phases.MainIco) {
phase = Phases.MainIco;
}
} else if (phase == Phases.PreStart) {
setDefaultParamsIfNeeded();
phase = Phases.PreIcoA;
}
}
function setDefaultParamsIfNeeded() internal {
if (bounty == address(0)) {
bounty = owner;
}
if (upgradeMaster == address(0)) {
upgradeMaster = owner;
}
if (pauseMaster == address(0)) {
pauseMaster = owner;
}
}
function computeOversoldAndAdjustPhase(uint256 newTotalSupply) internal returns (uint256 oversoldTokens) {
if ((phase == Phases.PreIcoA) &&
(newTotalSupply >= PRE_ICO_LIMIT)) {
phase = Phases.PreIcoB;
oversoldTokens = newTotalSupply.sub(PRE_ICO_LIMIT);
} else if (newTotalSupply >= TOTAL_LIMIT) {
phase = Phases.AfterIco;
oversoldTokens = newTotalSupply.sub(TOTAL_LIMIT);
} else {
oversoldTokens = 0;
}
return oversoldTokens;
}
function getRates() internal returns (Rates rates) {
if (phase == Phases.PreIcoA) {
rates.toSender = TO_SENDER_RATE_A;
rates.toOwner = TO_OWNER_RATE_A;
rates.toBounty = TO_BOUNTY_RATE_A;
rates.total = TOTAL_RATE_A;
} else if (phase == Phases.PreIcoB) {
rates.toSender = TO_SENDER_RATE_B;
rates.toOwner = TO_OWNER_RATE_B;
rates.toBounty = TO_BOUNTY_RATE_B;
rates.total = TOTAL_RATE_B;
} else {
rates.toSender = TO_SENDER_RATE;
rates.toOwner = TO_OWNER_RATE;
rates.toBounty = TO_BOUNTY_RATE;
rates.total = TOTAL_RATE;
}
return rates;
}
function logShiftAndBookAward() internal {
uint256 shiftAward;
if ((phase == Phases.PreIcoA) || (phase == Phases.PreIcoB)) {
shiftAward = PRE_OPENING_AWARD;
} else if (phase == Phases.MainIco) {
shiftAward = ICO_OPENING_AWARD;
} else {
shiftAward = ICO_CLOSING_AWARD;
returnAllowedTime = uint64(now + RETURN_WEI_PAUSE);
}
setWithdrawal(msg.sender, shiftAward);
NewPhase(phase);
}
/**
* @dev Transfer tokens to the specified address.
* @param _to The address to transfer to.
* @param _value The amount of tokens to be transferred.
* @return success/failure
*/
function transfer(address _to, uint256 _value)
whenNotPaused limitForOwner public returns (bool success)
{
return super.transfer(_to, _value);
}
/**
* @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 the amount of tokens to be transferred.
* @return success/failure
*/
function transferFrom(address _from, address _to, uint256 _value)
whenNotPaused limitForOwner public returns (bool success)
{
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Approve the specified address to spend the specified amount of tokens on behalf of the msg.sender.
* Use "increaseApproval" or "decreaseApproval" function to change the approval, if needed.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @return success/failure
*/
function approve(address _spender, uint256 _value)
whenNotPaused limitForOwner public returns (bool success)
{
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
return super.approve(_spender, _value);
}
/**
* @dev Increase the approval for the passed address to spend tokens on behalf of the msg.sender.
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the approval with.
* @return success/failure
*/
function increaseApproval(address _spender, uint _addedValue)
whenNotPaused limitForOwner public returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev Decrease the approval for the passed address to spend tokens on behalf of the msg.sender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the approval with.
* @return success/failure
*/
function decreaseApproval(address _spender, uint _subtractedValue)
whenNotPaused limitForOwner public returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
/*
* @dev Withdraw the allowed value (ethers) from the contract balance.
* @return success/failure
*/
function withdraw() whenNotPaused public returns (bool success) {
return super.withdraw();
}
/**
* @dev Throws if called when ICO is active.
*/
modifier whenClosed() {
require(phase == Phases.AfterIco);
_;
}
/**
* @dev Throws if called when ICO is completed.
*/
modifier whenNotClosed() {
require(phase != Phases.AfterIco);
_;
}
/**
* @dev Throws if called by the owner before ICO is completed.
*/
modifier limitForOwner() {
require((msg.sender != owner) || (phase == Phases.AfterIco));
_;
}
/**
* @dev Throws if called before returnAllowedTime.
*/
modifier afterWithdrawPause() {
require(now > returnAllowedTime);
_;
}
}
| Mint tokens and add them to the balance of the message.sender. Additional tokens are minted and added to the owner and the bounty balances. return success/failure/ | function create() payable whenNotClosed whenNotPaused public returns (bool success) {
require(msg.value > 0);
require(now >= preIcoOpeningTime);
Phases oldPhase = phase;
uint256 weiToParticipate = msg.value;
uint256 overpaidWei;
adjustPhaseBasedOnTime();
if (phase != Phases.AfterIco) {
Rates memory rates = getRates();
uint256 newTokens = weiToParticipate.mul(rates.total);
uint256 requestedSupply = totalSupply.add(newTokens);
uint256 oversoldTokens = computeOversoldAndAdjustPhase(requestedSupply);
overpaidWei = (oversoldTokens > 0) ? oversoldTokens.div(rates.total) : 0;
if (overpaidWei > 0) {
weiToParticipate = msg.value.sub(overpaidWei);
newTokens = weiToParticipate.mul(rates.total);
requestedSupply = totalSupply.add(newTokens);
}
balances[msg.sender] = balances[msg.sender].add(weiToParticipate.mul(rates.toSender));
balances[owner] = balances[owner].add(weiToParticipate.mul(rates.toOwner));
balances[bounty] = balances[bounty].add(weiToParticipate.mul(rates.toBounty));
owner.transfer(weiToParticipate);
if (overpaidWei > 0) {
setWithdrawal(msg.sender, overpaidWei);
}
NewFunds(msg.sender, weiToParticipate);
setWithdrawal(msg.sender, msg.value);
}
if (phase != oldPhase) {
logShiftAndBookAward();
}
return true;
}
| 12,815,288 |
// contracts/multisender.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.7;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
pragma solidity 0.5.7;
/**
* @title UpgradeabilityStorage
* @dev This contract holds all the necessary state variables to support the upgrade functionality
*/
contract UpgradeabilityStorage {
// Version name of the current implementation
string internal _version;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the version name of the current implementation
* @return string representing the name of the current version
*/
function version() public view returns (string memory) {
return _version;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
}
pragma solidity 0.5.7;
/**
* @title UpgradeabilityOwnerStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract UpgradeabilityOwnerStorage {
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
pragma solidity 0.5.7;
/**
* @title OwnedUpgradeabilityStorage
* @dev This is the storage necessary to perform upgradeable contracts.
* This means, required state variables for upgradeability purpose and eternal storage per se.
*/
contract OwnedUpgradeabilityStorage is UpgradeabilityOwnerStorage, UpgradeabilityStorage, EternalStorage {}
pragma solidity 0.5.7;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner(), "not an owner");
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[keccak256("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));
setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function setOwner(address newOwner) internal {
emit OwnershipTransferred(owner(), newOwner);
addressStorage[keccak256("owner")] = newOwner;
}
}
pragma solidity 0.5.7;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is EternalStorage, Ownable {
function pendingOwner() public view returns (address) {
return addressStorage[keccak256("pendingOwner")];
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner());
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
addressStorage[keccak256("pendingOwner")] = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner(), pendingOwner());
addressStorage[keccak256("owner")] = addressStorage[keccak256("pendingOwner")];
addressStorage[keccak256("pendingOwner")] = address(0);
}
}
pragma solidity 0.5.7;
/**
* @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;
}
}
pragma solidity 0.5.7;
contract Messages is EternalStorage {
struct Authorization {
address authorizedSigner;
uint256 expiration;
}
/**
* Domain separator encoding per EIP 712.
* keccak256(
* "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
* )
*/
bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;
/**
* Validator struct type encoding per EIP 712
* keccak256(
* "Authorization(address authorizedSigner,uint256 expiration)"
* )
*/
bytes32 private constant AUTHORIZATION_TYPEHASH = 0xe419504a688f0e6ea59c2708f49b2bbc10a2da71770bd6e1b324e39c73e7dc25;
/**
* Domain separator per EIP 712
*/
// bytes32 public DOMAIN_SEPARATOR;
function DOMAIN_SEPARATOR() public view returns(bytes32) {
bytes32 salt = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a558;
return keccak256(abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Multisender"),
keccak256("2.0"),
uintStorage[keccak256("chainId")],
address(this),
salt
));
}
/**
* @notice Calculates authorizationHash according to EIP 712.
* @param _authorizedSigner address of trustee
* @param _expiration expiration date
* @return bytes32 EIP 712 hash of _authorization.
*/
function hash(address _authorizedSigner, uint256 _expiration) public pure returns (bytes32) {
return keccak256(abi.encode(
AUTHORIZATION_TYPEHASH,
_authorizedSigner,
_expiration
));
}
/**
* @return the recovered address from the signature
*/
function recoverAddress(
bytes32 messageHash,
bytes memory signature
)
public
view
returns (address)
{
bytes32 r;
bytes32 s;
bytes1 v;
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := mload(add(signature, 0x60))
}
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
messageHash
));
return ecrecover(digest, uint8(v), r, s);
}
function getApprover(uint256 timestamp, bytes memory signature) public view returns(address) {
if (timestamp < now) {
return address(0);
}
bytes32 messageHash = hash(msg.sender, timestamp);
return recoverAddress(messageHash, signature);
}
}
pragma solidity 0.5.7;
/**
* @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);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public
view
returns (uint256);
function transferFrom(address from, address to, uint256 value)
public
returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract UpgradebleStormSender is
OwnedUpgradeabilityStorage,
Claimable,
Messages
{
using SafeMath for uint256;
event Multisended(uint256 total, address tokenAddress);
event ClaimedTokens(address token, address owner, uint256 balance);
event PurchaseVIP(address customer, uint256 tier);
modifier hasFee() {
uint256 contractFee = currentFee(msg.sender);
if (contractFee > 0) {
require(msg.value >= contractFee, "no fee");
}
_;
}
modifier validLists(uint256 _contributorsLength, uint256 _balancesLength) {
require(_contributorsLength > 0, "no contributors sent");
require(
_contributorsLength == _balancesLength,
"different arrays lengths"
);
_;
}
function() external payable {}
function initialize(
address _owner,
uint256 _fee,
uint256 _vipPrice0,
uint256 _vipPrice1,
uint256 _vipPrice2,
uint256 _chainId
) public {
require(!initialized() || msg.sender == owner());
setOwner(_owner);
setFee(_fee); // 0.05 ether fee
setVipPrice(0, _vipPrice0); // 1 eth
setVipPrice(1, _vipPrice1); // 5 eth
setVipPrice(2, _vipPrice2); // 10 eth
uintStorage[keccak256("chainId")] = _chainId;
boolStorage[keccak256("rs_multisender_initialized")] = true;
require(fee() >= 0.01 ether);
uintStorage[keccak256("referralFee")] = 0.01 ether;
}
function initialized() public view returns (bool) {
return boolStorage[keccak256("rs_multisender_initialized")];
}
function fee() public view returns (uint256) {
return uintStorage[keccak256("fee")];
}
function currentFee(address _customer) public view returns (uint256) {
if (getUnlimAccess(_customer) >= block.timestamp) {
return 0;
}
return fee();
}
function setFee(uint256 _newStep) public onlyOwner {
require(_newStep != 0);
uintStorage[keccak256("fee")] = _newStep;
}
function tokenFallback(address _from, uint256 _value, bytes memory _data)
public
{}
function _checkFee(address _user, address payable _referral) internal {
uint256 contractFee = currentFee(_user);
if (contractFee > 0) {
require(msg.value >= contractFee, "no fee");
if (_referral != address(0)) {
_referral.send(referralFee());
}
}
}
function multisendToken(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total,
address payable _referral
) external payable validLists(_contributors.length, _balances.length) {
bool isGoodToken;
bytes memory data;
_checkFee(msg.sender, _referral);
uint256 change = 0;
ERC20 erc20token = ERC20(_token);
// bytes4 transferFrom = 0x23b872dd;
(isGoodToken, data) = _token.call(
abi.encodeWithSelector(
0x23b872dd,
msg.sender,
address(this),
_total
)
);
require(isGoodToken, "transferFrom failed");
if (data.length > 0) {
bool success = abi.decode(data, (bool));
require(success, "not enough allowed tokens");
}
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transfer.selector,
_contributors[i],
_balances[i]
)
);
if (!success) {
change += _balances[i];
}
}
if (change != 0) {
erc20token.transfer(msg.sender, change);
}
emit Multisended(_total, _token);
}
function findBadAddressesForBurners(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total
)
external
payable
validLists(_contributors.length, _balances.length)
hasFee
returns (address[] memory badAddresses, uint256[] memory badBalances)
{
badAddresses = new address[](_contributors.length);
badBalances = new uint256[](_contributors.length);
ERC20 erc20token = ERC20(_token);
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transferFrom.selector,
msg.sender,
_contributors[i],
_balances[i]
)
);
if (!success) {
badAddresses[i] = _contributors[i];
badBalances[i] = _balances[i];
}
}
}
function multisendTokenForBurners(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total,
address payable _referral
) external payable validLists(_contributors.length, _balances.length) {
_checkFee(msg.sender, _referral);
ERC20 erc20token = ERC20(_token);
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transferFrom.selector,
msg.sender,
_contributors[i],
_balances[i]
)
);
}
emit Multisended(_total, _token);
}
function multisendTokenForBurnersWithSignature(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total,
address payable _referral,
bytes calldata _signature,
uint256 _timestamp
) external payable {
address tokenHolder = getApprover(_timestamp, _signature);
require(
tokenHolder != address(0),
"the signature is invalid or has expired"
);
require(_contributors.length > 0, "no contributors sent");
require(
_contributors.length == _balances.length,
"different arrays lengths"
);
// require(msg.value >= currentFee(tokenHolder), "no fee");
_checkFee(tokenHolder, _referral);
ERC20 erc20token = ERC20(_token);
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transferFrom.selector,
tokenHolder,
_contributors[i],
_balances[i]
)
);
}
emit Multisended(_total, _token);
}
function multisendTokenWithSignature(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total,
address payable _referral,
bytes calldata _signature,
uint256 _timestamp
) external payable {
bool isGoodToken;
address tokenHolder = getApprover(_timestamp, _signature);
require(
tokenHolder != address(0),
"the signature is invalid or has expired"
);
require(_contributors.length > 0, "no contributors sent");
require(
_contributors.length == _balances.length,
"different arrays lengths"
);
_checkFee(tokenHolder, _referral);
uint256 change = 0;
(isGoodToken, ) = _token.call(
abi.encodeWithSelector(
0x23b872dd,
tokenHolder,
address(this),
_total
)
);
require(isGoodToken, "not enough allowed tokens");
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
// transfer
0xa9059cbb,
_contributors[i],
_balances[i]
)
);
if (!success) {
change += _balances[i];
}
}
if (change != 0) {
_token.call(
abi.encodeWithSelector(
// transfer
0xa9059cbb,
tokenHolder,
change
)
);
}
emit Multisended(_total, _token);
}
// DONT USE THIS METHOD, only for eth_call
function tokenFindBadAddresses(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total
)
external
payable
validLists(_contributors.length, _balances.length)
hasFee
returns (address[] memory badAddresses, uint256[] memory badBalances)
{
badAddresses = new address[](_contributors.length);
badBalances = new uint256[](_contributors.length);
ERC20 erc20token = ERC20(_token);
bool isGoodToken;
(isGoodToken, ) = _token.call(
abi.encodeWithSelector(
0x23b872dd,
msg.sender,
address(this),
_total
)
);
// erc20token.transferFrom(msg.sender, address(this), _total);
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transfer.selector,
_contributors[i],
_balances[i]
)
);
if (!success) {
badAddresses[i] = _contributors[i];
badBalances[i] = _balances[i];
}
}
}
// DONT USE THIS METHOD, only for eth_call
function etherFindBadAddresses(
address payable[] calldata _contributors,
uint256[] calldata _balances
)
external
payable
validLists(_contributors.length, _balances.length)
returns (address[] memory badAddresses, uint256[] memory badBalances)
{
badAddresses = new address[](_contributors.length);
badBalances = new uint256[](_contributors.length);
uint256 _total = msg.value;
uint256 _contractFee = currentFee(msg.sender);
_total = _total.sub(_contractFee);
for (uint256 i = 0; i < _contributors.length; i++) {
bool _success = _contributors[i].send(_balances[i]);
if (!_success) {
badAddresses[i] = _contributors[i];
badBalances[i] = _balances[i];
} else {
_total = _total.sub(_balances[i]);
}
}
}
function multisendEther(
address payable[] calldata _contributors,
uint256[] calldata _balances
) external payable validLists(_contributors.length, _balances.length) {
uint256 _contractBalanceBefore = address(this).balance.sub(msg.value);
uint256 _total = msg.value;
uint256 _contractFee = currentFee(msg.sender);
_total = _total.sub(_contractFee);
for (uint256 i = 0; i < _contributors.length; i++) {
bool _success = _contributors[i].send(_balances[i]);
if (_success) {
_total = _total.sub(_balances[i]);
}
}
uint256 _contractBalanceAfter = address(this).balance;
// assert. Just for sure
require(
_contractBalanceAfter >= _contractBalanceBefore.add(_contractFee),
"don’t try to take the contract money"
);
emit Multisended(_total, 0x000000000000000000000000000000000000bEEF);
}
function setVipPrice(uint256 _tier, uint256 _price) public onlyOwner {
uintStorage[keccak256(abi.encodePacked("vip", _tier))] = _price;
}
function setAddressToVip(address _address, uint256 _tier)
external
onlyOwner
{
setUnlimAccess(_address, _tier);
emit PurchaseVIP(msg.sender, _tier);
}
function buyVip(uint256 _tier) external payable {
require(
msg.value >= uintStorage[keccak256(abi.encodePacked("vip", _tier))]
);
setUnlimAccess(msg.sender, _tier);
emit PurchaseVIP(msg.sender, _tier);
}
function setReferralFee(uint256 _newFee) external onlyOwner {
require(fee() >= _newFee);
uintStorage[keccak256("referralFee")] = _newFee;
}
function referralFee() public view returns (uint256) {
return uintStorage[keccak256("referralFee")];
}
function getVipPrice(uint256 _tier) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("vip", _tier))];
}
function getAllVipPrices()
external
view
returns (uint256 tier0, uint256 tier1, uint256 tier2)
{
return (
uintStorage[keccak256(abi.encodePacked("vip", uint256(0)))],
uintStorage[keccak256(abi.encodePacked("vip", uint256(1)))],
uintStorage[keccak256(abi.encodePacked("vip", uint256(2)))]
);
}
function claimTokens(address _token, uint256 _amount) external onlyOwner {
address payable ownerPayable = address(uint160(owner()));
uint256 amount = _amount;
if (_amount == 0) {
amount = address(this).balance;
}
if (_token == address(0)) {
ownerPayable.transfer(amount);
return;
}
ERC20 erc20token = ERC20(_token);
amount = erc20token.balanceOf(address(this));
erc20token.transfer(ownerPayable, amount);
emit ClaimedTokens(_token, ownerPayable, amount);
}
function getDeadline(uint256 _tier) public view returns (uint256) {
// 1 day
if (_tier == 0) {
return block.timestamp + 1 days;
}
// 7 days
if (_tier == 1) {
return block.timestamp + 7 days;
}
// Lifetime
if (_tier == 2) {
return block.timestamp + 30 days;
}
return 0;
}
function getUnlimAccess(address customer) public view returns (uint256) {
return
uintStorage[keccak256(abi.encodePacked("unlimAccess", customer))];
}
function setUnlimAccess(address customer, uint256 _tier) private {
uintStorage[keccak256(
abi.encodePacked("unlimAccess", customer)
)] = getDeadline(_tier);
}
function exploreETHBalances(address[] calldata targets)
external
view
returns (uint256[] memory balances)
{
balances = new uint256[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
balances[i] = targets[i].balance;
}
}
function exploreERC20Balances(ERC20 token, address[] calldata targets)
external
view
returns (uint256[] memory balances)
{
balances = new uint256[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
balances[i] = token.balanceOf(targets[i]);
}
}
} | bytes4 transferFrom = 0x23b872dd; | function multisendToken(
address _token,
address[] calldata _contributors,
uint256[] calldata _balances,
uint256 _total,
address payable _referral
) external payable validLists(_contributors.length, _balances.length) {
bool isGoodToken;
bytes memory data;
_checkFee(msg.sender, _referral);
uint256 change = 0;
ERC20 erc20token = ERC20(_token);
(isGoodToken, data) = _token.call(
abi.encodeWithSelector(
0x23b872dd,
msg.sender,
address(this),
_total
)
);
require(isGoodToken, "transferFrom failed");
if (data.length > 0) {
bool success = abi.decode(data, (bool));
require(success, "not enough allowed tokens");
}
for (uint256 i = 0; i < _contributors.length; i++) {
(bool success, ) = _token.call(
abi.encodeWithSelector(
erc20token.transfer.selector,
_contributors[i],
_balances[i]
)
);
if (!success) {
change += _balances[i];
}
}
if (change != 0) {
erc20token.transfer(msg.sender, change);
}
emit Multisended(_total, _token);
}
| 13,633,996 |
./partial_match/44787/0x5FA546fEE65fDB957f9098f3F4ae765Aeee8f50B/sources/src/interfaces/IMoolaLendingPoolAddressesProvider.sol | LendingPoolAddressesProvider contract Main registry of addresses part of or connected to the protocol, including permissioned roles - Acting also as factory of proxies and admin of those, so with right to change its implementations - Owned by the Aave Governance Aave/ | interface IMoolaLendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
pragma solidity ^0.8.10;
} | 16,953,393 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./IW3lockEAPOwnersClub.sol";
/**
* @title Delegate Proxy
* @notice delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users
*/
contract OwnableDelegateProxy {
}
/**
* @title Proxy Registry
* @notice map address to the delegate proxy
*/
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @author a42
* @title W3lockEAPTicket
* @notice ERC721 contract
*/
contract W3lockEAPTicket is ERC721, Ownable, Pausable {
/**
* Libraries
*/
using Counters for Counters.Counter;
/**
* Events
*/
event Withdraw(address indexed operator);
event SetFee(uint256 fee);
event SetCap(uint256 cap);
event IncrementBatch(uint256 batch);
event SetBaseTokenURI(string baseTokenURI);
event SetContractURI(string contractURI);
event SetProxyRegistryAddress(address indexed proxyRegistryAddress);
event SetOwnersClubNFTAddress(address indexed ownersClubNFTAddress);
event Burn(address indexed from, uint256 tokenId);
event SetIsMintingRestricted(bool isRestricted);
/**
* Public Variables
*/
address public proxyRegistryAddress;
bool public isMintingRestricted;
string public baseTokenURI;
string public contractURI;
uint256 public cap;
uint256 public fee;
mapping(uint256 => uint256) public batchNumberOf;
/**
* Private Variables
*/
Counters.Counter private _nextTokenId;
Counters.Counter private _nextBatch;
Counters.Counter private _totalSupply;
IW3lockEAPOwnersClub private ownersClub;
/**
* Modifiers
*/
modifier onlyTokenOwner(uint256 _tokenId) {
require(ownerOf(_tokenId) == _msgSender(), "Only Token Owner");
_;
}
modifier whenMintingNotRestricted() {
if (isMintingRestricted)
require(_msgSender() == owner(), "Only Owner Mint Allowed");
_;
}
/**
* Constructor
* @notice Owner address will be automatically set to deployer address in the parent contract (Ownable)
* @param _baseTokenURI - base uri to be set as a initial baseTokenURI
* @param _contractURI - base contract uri to be set as a initial contractURI
* @param _proxyRegistryAddress - proxy address to be set as a initial proxyRegistryAddress
* @param _ownersClubNFTAddress - owners club contract address to be set as a initial ownersClub
*/
constructor(
string memory _baseTokenURI,
string memory _contractURI,
address _proxyRegistryAddress,
address _ownersClubNFTAddress
) ERC721("W3lockEAPTicket", "W3LET") {
baseTokenURI = _baseTokenURI;
contractURI = _contractURI;
proxyRegistryAddress = _proxyRegistryAddress;
ownersClub = IW3lockEAPOwnersClub(_ownersClubNFTAddress);
// nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter
_nextTokenId.increment();
_nextBatch.increment();
_totalSupply.increment();
}
/**
* Receive function
*/
receive() external payable {}
/**
* Fallback function
*/
fallback() external payable {}
/**
* @notice Set contractURI
* @dev onlyOwner
* @param _contractURI - URI to be set as a new contractURI
*/
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
emit SetContractURI(_contractURI);
}
/**
* @notice Set baseTokenURI for this contract
* @dev onlyOwner
* @param _baseTokenURI - URI to be set as a new baseTokenURI
*/
function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
emit SetBaseTokenURI(_baseTokenURI);
}
/**
* @notice Register proxy registry address
* @dev onlyOwner
* @param _proxyRegistryAddress - address to be set as a new proxyRegistryAddress
*/
function setProxyRegistryAddress(address _proxyRegistryAddress)
external
onlyOwner
{
proxyRegistryAddress = _proxyRegistryAddress;
emit SetProxyRegistryAddress(_proxyRegistryAddress);
}
/**
* @notice Set new supply cap
* @dev onlyOwer
* @param _cap - new supply cap
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit SetCap(_cap);
}
/**
* @notice Set fee
* @dev onlyOwner
* @param _fee - fee to be set as a new fee
*/
function setFee(uint256 _fee) external onlyOwner {
fee = _fee;
emit SetFee(_fee);
}
/**
* @notice Set new Owners Club NFT contract address
* @dev onlyOwner
*/
function setOwnersClubNFTAddress(address _ownersClubNFTAddress)
external
onlyOwner
{
ownersClub = IW3lockEAPOwnersClub(_ownersClubNFTAddress);
emit SetOwnersClubNFTAddress(_ownersClubNFTAddress);
}
/**
* @notice Set isMintingRestricted flag
* @dev onlyOwner
* @param _isRestricted - boolean value to be set as minting restriction mode
*/
function setIsMintingRestricted(bool _isRestricted) external onlyOwner {
isMintingRestricted = _isRestricted;
emit SetIsMintingRestricted(_isRestricted);
}
/**
* @notice increment batch
* @dev onlyOwner
*/
function incrementBatch() external onlyOwner {
_nextBatch.increment();
emit IncrementBatch(_nextBatch.current());
}
/**
* @notice Transfer balance in contract to the owner address
* @dev onlyOwner
*/
function withdraw() external onlyOwner {
require(address(this).balance > 0, "Not Enough Balance Of Contract");
(bool success, ) = owner().call{ value: address(this).balance }("");
require(success, "Transfer Failed");
emit Withdraw(msg.sender);
}
/**
* @notice Pause this contract
* @dev onlyOwner
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpause this contract
* @dev onlyOwner
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Return totalSupply
* @return uint256
*/
function totalSupply() public view returns (uint256) {
return _totalSupply.current() - 1;
}
/**
* @notice Return total minted count
* @return uint256
*/
function totalMinted() public view returns (uint256) {
return _nextTokenId.current() - 1;
}
/**
* @notice Return bool if the token exists
* @param _tokenId - tokenId to be check if exists
* @return bool
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
/**
* @notice Return current batch
* @return uint256
*/
function batchNumber() public view returns (uint256) {
return _nextBatch.current();
}
/**
* @notice Mint token
* @dev whenNotPaused, onlyOwnerMintAllowed
*/
function mint() public payable whenNotPaused whenMintingNotRestricted {
mintTo(_msgSender());
}
/**
* @notice Mint token to the beneficiary
* @dev whenNotPaused, onlyOwnerMintAllowed
* @param _beneficiary - address eligible to get the token
*/
function mintTo(address _beneficiary)
public
payable
whenNotPaused
whenMintingNotRestricted
{
require(msg.value >= fee, "Insufficient Fee");
require(totalMinted() < cap, "Capped");
uint256 tokenId = _nextTokenId.current();
_safeMint(_beneficiary, tokenId);
_nextTokenId.increment();
_totalSupply.increment();
batchNumberOf[tokenId] = batchNumber();
}
/**
* @notice Burn token and mint owners nft to the msg sender
* @dev onlyTokenOwner, whenNotPaused
* @param _tokenId - tokenId
*/
function burn(uint256 _tokenId)
public
onlyTokenOwner(_tokenId)
whenNotPaused
{
uint256 tokenBatchNumber = batchNumberOf[_tokenId];
_burn(_tokenId);
ownersClub.mintTo(_tokenId, tokenBatchNumber, _msgSender());
delete batchNumberOf[_tokenId];
_totalSupply.decrement();
emit Burn(_msgSender(), _tokenId);
}
/**
* @notice Check if the owner approve the operator address
* @dev Override to allow proxy contracts for gas less approval
* @param _owner - owner address
* @param _operator - operator address
* @return bool
*/
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return super.isApprovedForAll(_owner, _operator);
}
/**
* @notice See {ERC721-_beforeTokenTransfer}
* @dev Override to check paused status
* @param _from - address which wants to transfer the token by tokenId
* @param _to - address eligible to get the token
* @param _tokenId - tokenId
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
/**
* @notice See {ERC721-_baseURI}
* @dev Override to return baseTokenURI set by the owner
* @return string memory
*/
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
interface IW3lockEAPOwnersClub {
function mintTo(
uint256 _tokenId,
uint256 _batchNumber,
address _beneficiary
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | See {ERC721-_baseURI} Override to return baseTokenURI set by the owner return string memory/ | function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
| 10,302,199 |
/**
*Submitted for verification at Etherscan.io on 2017-01-02
*/
/* Copyright (C) Etherplay <[email protected]> - All Rights Reserved */
pragma solidity ^0.4.2;
contract CompetitionStore {
/////////////////////////////////////////////////////////////////// DATA /////////////////////////////////////////////////////////////
//player's submission store the info required to verify its accuracy
struct Submission{
uint32 score;
uint32 durationRoundedDown; // duration in second of the game session
uint32 version; // version of the game used
uint64 seed; //seed used
uint64 submitBlockNumber; // blockNumber at which the submission is processed
bytes32 proofHash;//sha256 of proof : to save gas, the proof is not saved directly in the contract. Instead its hash is saved. The actual proof will be saved on a server. The player could potentially save it too.
}
//player start game parameter
struct Start{
uint8 competitionIndex; //competition index (0 or 1) there is only 2 current competition per game, one is active, the other one being the older one which might have pending verification
uint32 version; //version of the game that the player score is based on
uint64 seed; // the seed used for the game session
uint64 time; // start time , used to check if the player is not taking too long to submit its score
}
// the values representing each competition
struct Competition{
uint8 numPastBlocks;// number of past block allowed, 1 is the minimum since you can only get the hash of a past block. Allow player to start play instantunously
uint8 houseDivider; // how much the house takes : 4 means house take 1/4 (25%)
uint16 lag; // define how much extra time is allowed to submit a score (to accomodate block time and delays)
uint32 verificationWaitTime;// wait time allowed for submission past competition's end time
uint32 numPlayers;//current number of player that submited a score
uint32 version; //the version of the game used for that competition, a hash of the code is published in the log upon changing
uint32 previousVersion; // previousVersion to allow smooth update upon version change
uint64 versionChangeBlockNumber;
uint64 switchBlockNumber; // the blockNumber at which the competition started
uint64 endTime;//The time at which the competition is set to finish. No start can happen after that and the competition cannot be aborted before that
uint88 price; // the price for that competition, do not change
uint128 jackpot; // the current jackpot for that competition, this jackpot is then shared among the developer (in the deposit account for funding development) and the winners (see houseDivider))
uint32[] rewardsDistribution; // the length of it define how many winners there is and the distribution of the reward is the value for each index divided by the total
mapping (address => Submission) submissions; //only one submission per player per competition
address[] players; // contain the list of players that submited a score for that competition
}
struct Game{
mapping (address => Start) starts; // only 1 start per player, further override the current
Competition[2] competitions; // 2 competitions only to save gas, overrite each other upon going to next competition
uint8 currentCompetitionIndex; //can only be 1 or 0 (switch operation : 1 - currentCompetitionIndex)
}
mapping (string => Game) games;
address organiser; // admin having control of the reward
address depositAccount; // is the receiver of the house part of the jackpot (see houseDivider) Can only be changed by the depositAccount.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////// EVENTS /////////////////////////////////////////////////////////////
//event logging the hash of the game code for a particular version
event VersionChange(
string indexed gameID,
uint32 indexed version,
bytes32 codeHash // the sha256 of the game code as used by the player
);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////// PLAYERS ACTIONS /////////////////////////////////////////////////////////////
/*
The seed is computed from the block hash and the sender address
While the seed can be predicted for few block away (see : numPastBlocks) this is has no much relevance since a game session have a bigger duration,
Remember this is not gambling game, this is a skill game, seed is only a small part of the game outcome
*/
function computeSeed(uint64 blockNumber, address player) internal constant returns(uint64 seed){
return uint64(sha3(block.blockhash(blockNumber),block.blockhash(blockNumber-1),block.blockhash(blockNumber-2),block.blockhash(blockNumber-3),block.blockhash(blockNumber-4),block.blockhash(blockNumber-5),player));
}
/*
probe the current state of the competition so player can start playing right away (need to commit a tx too to ensure its play will be considered though)
*/
function getSeedAndState(string gameID, address player) constant returns(uint64 seed, uint64 blockNumber, uint8 competitionIndex, uint32 version, uint64 endTime, uint88 price, uint32 myBestScore, uint64 competitionBlockNumber, uint64 registeredSeed){
var game = games[gameID];
competitionIndex = game.currentCompetitionIndex;
var competition = game.competitions[competitionIndex];
blockNumber = uint64(block.number-1);
seed = computeSeed(blockNumber, player);
version = competition.version;
endTime = competition.endTime;
price = competition.price;
competitionBlockNumber = competition.switchBlockNumber;
if (competition.submissions[player].submitBlockNumber >= competition.switchBlockNumber){
myBestScore = competition.submissions[player].score;
}else{
myBestScore = 0;
}
registeredSeed = game.starts[player].seed;
}
function start(string gameID, uint64 blockNumber,uint8 competitionIndex, uint32 version) payable {
var game = games[gameID];
var competition = game.competitions[competitionIndex];
if(msg.value != competition.price){
throw;
}
if(
competition.endTime <= now || //block play when time is up
competitionIndex != game.currentCompetitionIndex || //start happen just after a switch // should not be possible since endTime already ensure that a new competition cannot start before the end of the first
version != competition.version && (version != competition.previousVersion || block.number > competition.versionChangeBlockNumber) || //ensure version is same as current (or previous if versionChangeBlockNumber is recent)
block.number >= competition.numPastBlocks && block.number - competition.numPastBlocks > blockNumber //ensure start is not too old
){
//if ether was sent, send it back if possible, else throw
if(msg.value != 0 && !msg.sender.send(msg.value)){
throw;
}
return;
}
competition.jackpot += uint128(msg.value); //increase the jackpot
//save the start params
game.starts[msg.sender] = Start({
seed: computeSeed(blockNumber,msg.sender)
, time : uint64(now)
, competitionIndex : competitionIndex
, version : version
});
}
function submit(string gameID, uint64 seed, uint32 score, uint32 durationRoundedDown, bytes32 proofHash){
var game = games[gameID];
var gameStart = game.starts[msg.sender];
//seed should be same, else it means double start and this one executing is from the old one
if(gameStart.seed != seed){
return;
}
var competition = game.competitions[gameStart.competitionIndex];
// game should not take too long to be submited
if(now - gameStart.time > durationRoundedDown + competition.lag){
return;
}
if(now >= competition.endTime + competition.verificationWaitTime){
return; //this ensure verifier to get all the score at that time (should never be there though as game should ensure a maximumTime < verificationWaitTime)
}
var submission = competition.submissions[msg.sender];
if(submission.submitBlockNumber < competition.switchBlockNumber){
if(competition.numPlayers >= 4294967295){ //unlikely but if that happen this is for now the best place to stop
return;
}
}else if (score <= submission.score){
return;
}
var players = competition.players;
//if player did not submit score yet => add player to list
if(submission.submitBlockNumber < competition.switchBlockNumber){
var currentNumPlayer = competition.numPlayers;
if(currentNumPlayer >= players.length){
players.push(msg.sender);
}else{
players[currentNumPlayer] = msg.sender;
}
competition.numPlayers = currentNumPlayer + 1;
}
competition.submissions[msg.sender] = Submission({
proofHash:proofHash,
seed:gameStart.seed,
score:score,
durationRoundedDown:durationRoundedDown,
submitBlockNumber:uint64(block.number),
version:gameStart.version
});
}
/*
accept donation payment : this increase the jackpot of the currentCompetition of the specified game
*/
function increaseJackpot(string gameID) payable{
var game = games[gameID];
game.competitions[game.currentCompetitionIndex].jackpot += uint128(msg.value); //extra ether is lost but this is not going to happen :)
}
//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// PRIVATE ///////////////////////////////////////////
function CompetitionStore(){
organiser = msg.sender;
depositAccount = msg.sender;
}
//give a starting jackpot by sending ether to the transaction
function _startNextCompetition(string gameID, uint32 version, uint88 price, uint8 numPastBlocks, uint8 houseDivider, uint16 lag, uint64 duration, uint32 verificationWaitTime, bytes32 codeHash, uint32[] rewardsDistribution) payable{
if(msg.sender != organiser){
throw;
}
var game = games[gameID];
var newCompetition = game.competitions[1 - game.currentCompetitionIndex];
var currentCompetition = game.competitions[game.currentCompetitionIndex];
//do not allow to switch if endTime is not over
if(currentCompetition.endTime >= now){
throw;
}
//block switch if reward was not called (numPlayers > 0)
if(newCompetition.numPlayers > 0){
throw;
}
if(houseDivider == 0){
throw;
}
if(numPastBlocks < 1){
throw;
}
if(rewardsDistribution.length == 0 || rewardsDistribution.length > 64){ // do not risk gas shortage on reward
throw;
}
//ensure rewardsDistribution give always something and do not give more to a lower scoring player
uint32 prev = 0;
for(uint8 i = 0; i < rewardsDistribution.length; i++){
if(rewardsDistribution[i] == 0 || (prev != 0 && rewardsDistribution[i] > prev)){
throw;
}
prev = rewardsDistribution[i];
}
if(version != currentCompetition.version){
VersionChange(gameID,version,codeHash);
}
game.currentCompetitionIndex = 1 - game.currentCompetitionIndex;
newCompetition.switchBlockNumber = uint64(block.number);
newCompetition.previousVersion = 0;
newCompetition.versionChangeBlockNumber = 0;
newCompetition.version = version;
newCompetition.price = price;
newCompetition.numPastBlocks = numPastBlocks;
newCompetition.rewardsDistribution = rewardsDistribution;
newCompetition.houseDivider = houseDivider;
newCompetition.lag = lag;
newCompetition.jackpot += uint128(msg.value); //extra ether is lost but this is not going to happen :)
newCompetition.endTime = uint64(now) + duration;
newCompetition.verificationWaitTime = verificationWaitTime;
}
function _setBugFixVersion(string gameID, uint32 version, bytes32 codeHash, uint32 numBlockAllowedForPastVersion){
if(msg.sender != organiser){
throw;
}
var game = games[gameID];
var competition = game.competitions[game.currentCompetitionIndex];
if(version <= competition.version){ // a bug fix should be a new version (greater than previous version)
throw;
}
if(competition.endTime <= now){ // cannot bugFix a competition that already ended
return;
}
competition.previousVersion = competition.version;
competition.versionChangeBlockNumber = uint64(block.number + numBlockAllowedForPastVersion);
competition.version = version;
VersionChange(gameID,version,codeHash);
}
function _setLagParams(string gameID, uint16 lag, uint8 numPastBlocks){
if(msg.sender != organiser){
throw;
}
if(numPastBlocks < 1){
throw;
}
var game = games[gameID];
var competition = game.competitions[game.currentCompetitionIndex];
competition.numPastBlocks = numPastBlocks;
competition.lag = lag;
}
function _rewardWinners(string gameID, uint8 competitionIndex, address[] winners){
if(msg.sender != organiser){
throw;
}
var competition = games[gameID].competitions[competitionIndex];
//ensure time has passed so that players who started near the end can finish their session
//game should be made to ensure termination before verificationWaitTime, it is the game responsability
if(int(now) - competition.endTime < competition.verificationWaitTime){
throw;
}
if( competition.jackpot > 0){ // if there is no jackpot skip
var rewardsDistribution = competition.rewardsDistribution;
uint8 numWinners = uint8(rewardsDistribution.length);
if(numWinners > uint8(winners.length)){
numWinners = uint8(winners.length);
}
uint128 forHouse = competition.jackpot;
if(numWinners > 0 && competition.houseDivider > 1){ //in case there is no winners (no players or only cheaters), the house takes all
forHouse = forHouse / competition.houseDivider;
uint128 forWinners = competition.jackpot - forHouse;
uint64 total = 0;
for(uint8 i=0; i<numWinners; i++){ // distribute all the winning even if there is not all the winners
total += rewardsDistribution[i];
}
for(uint8 j=0; j<numWinners; j++){
uint128 value = (forWinners * rewardsDistribution[j]) / total;
if(!winners[j].send(value)){ // if fail give to house
forHouse = forHouse + value;
}
}
}
if(!depositAccount.send(forHouse)){
//in case sending to house failed
var nextCompetition = games[gameID].competitions[1 - competitionIndex];
nextCompetition.jackpot = nextCompetition.jackpot + forHouse;
}
competition.jackpot = 0;
}
competition.numPlayers = 0;
}
/*
allow to change the depositAccount of the house share, only the depositAccount can change it, depositAccount == organizer at creation
*/
function _setDepositAccount(address newDepositAccount){
if(depositAccount != msg.sender){
throw;
}
depositAccount = newDepositAccount;
}
/*
allow to change the organiser, in case this need be
*/
function _setOrganiser(address newOrganiser){
if(organiser != msg.sender){
throw;
}
organiser = newOrganiser;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////// OTHER CONSTANT CALLS TO PROBE VALUES ////////////////////////////////////////////////////
function getPlayerSubmissionFromCompetition(string gameID, uint8 competitionIndex, address playerAddress) constant returns(uint32 score, uint64 seed, uint32 duration, bytes32 proofHash, uint32 version, uint64 submitBlockNumber){
var submission = games[gameID].competitions[competitionIndex].submissions[playerAddress];
score = submission.score;
seed = submission.seed;
duration = submission.durationRoundedDown;
proofHash = submission.proofHash;
version = submission.version;
submitBlockNumber =submission.submitBlockNumber;
}
function getPlayersFromCompetition(string gameID, uint8 competitionIndex) constant returns(address[] playerAddresses, uint32 num){
var competition = games[gameID].competitions[competitionIndex];
playerAddresses = competition.players;
num = competition.numPlayers;
}
function getCompetitionValues(string gameID, uint8 competitionIndex) constant returns (
uint128 jackpot,
uint88 price,
uint32 version,
uint8 numPastBlocks,
uint64 switchBlockNumber,
uint32 numPlayers,
uint32[] rewardsDistribution,
uint8 houseDivider,
uint16 lag,
uint64 endTime,
uint32 verificationWaitTime,
uint8 _competitionIndex
){
var competition = games[gameID].competitions[competitionIndex];
jackpot = competition.jackpot;
price = competition.price;
version = competition.version;
numPastBlocks = competition.numPastBlocks;
switchBlockNumber = competition.switchBlockNumber;
numPlayers = competition.numPlayers;
rewardsDistribution = competition.rewardsDistribution;
houseDivider = competition.houseDivider;
lag = competition.lag;
endTime = competition.endTime;
verificationWaitTime = competition.verificationWaitTime;
_competitionIndex = competitionIndex;
}
function getCurrentCompetitionValues(string gameID) constant returns (
uint128 jackpot,
uint88 price,
uint32 version,
uint8 numPastBlocks,
uint64 switchBlockNumber,
uint32 numPlayers,
uint32[] rewardsDistribution,
uint8 houseDivider,
uint16 lag,
uint64 endTime,
uint32 verificationWaitTime,
uint8 _competitionIndex
)
{
return getCompetitionValues(gameID,games[gameID].currentCompetitionIndex);
}
}
| seed should be same, else it means double start and this one executing is from the old one game should not take too long to be submited | function submit(string gameID, uint64 seed, uint32 score, uint32 durationRoundedDown, bytes32 proofHash){
var game = games[gameID];
var gameStart = game.starts[msg.sender];
if(gameStart.seed != seed){
return;
}
var competition = game.competitions[gameStart.competitionIndex];
if(now - gameStart.time > durationRoundedDown + competition.lag){
return;
}
if(now >= competition.endTime + competition.verificationWaitTime){
}
var submission = competition.submissions[msg.sender];
if(submission.submitBlockNumber < competition.switchBlockNumber){
return;
}
return;
}
var players = competition.players;
| 12,973,087 |
./full_match/1/0x2Cb88C9574F1bb8A15F8718ae41DEb651dcA0283/sources/contracts/VstSaleContract.sol | 如果是二次售卖,需要是token owner或者平台 如果是第一次售卖,需要是token的铸造人或者平台 | function sale(uint256 _tokenId, uint256[] memory _settings, address[] memory _addrs) public override {
uint _price = _settings[0];
address _quote = _addrs[0];
require(erc721.ownerOf(_tokenId) != address(0), "VSC_No_Exists_Token");
require(_price > 0, "VSC_Invalid_Price");
uint256 soldTimes = vsNft.getSoldTimes(_tokenId);
address tokenOwner = erc721.ownerOf(_tokenId);
address sender = tx.origin;
if (soldTimes > 0) {
require(tokenOwner == sender || owner() == sender, "VSC_not_tokenowner_platform");
require(vsNft.tokenMeta(_tokenId).minter == sender || tokenOwner == sender || owner() == sender, "VSC_not_tokenowner_platform");
}
TokenSaleMeta storage meta = tokenSaleMeta[_tokenId];
meta.id = _tokenId;
meta.price = _price;
meta.quote = _quote;
meta.sale = true;
meta.owner = tokenOwner;
emit LogTokenSale(_tokenId, sender, true, _quote, _price);
}
| 8,416,078 |
./partial_match/3/0xb7E92c14F753425DdF7Cd334DEbd78a0714c5c2A/sources/UTOCOIN.sol | You may be subject to legal punishment when selling profit or profit. KMONG OMD([email protected]) | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| 5,122,199 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import {IERC721} from "./../interfaces/IERC721.sol";
import {IERC721BatchTransfer} from "./../interfaces/IERC721BatchTransfer.sol";
import {IERC721Mintable} from "./../interfaces/IERC721Mintable.sol";
import {IERC721Deliverable} from "./../interfaces/IERC721Deliverable.sol";
import {IERC721Burnable} from "./../interfaces/IERC721Burnable.sol";
import {IERC721Receiver} from "./../interfaces/IERC721Receiver.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ProxyInitialization} from "./../../../proxy/libraries/ProxyInitialization.sol";
import {InterfaceDetectionStorage} from "./../../../introspection/libraries/InterfaceDetectionStorage.sol";
library ERC721Storage {
using Address for address;
using ERC721Storage for ERC721Storage.Layout;
using InterfaceDetectionStorage for InterfaceDetectionStorage.Layout;
struct Layout {
mapping(uint256 => uint256) owners;
mapping(address => uint256) balances;
mapping(uint256 => address) approvals;
mapping(address => mapping(address => bool)) operators;
}
bytes32 internal constant LAYOUT_STORAGE_SLOT = bytes32(uint256(keccak256("animoca.token.ERC721.ERC721.storage")) - 1);
bytes4 internal constant ERC721_RECEIVED = IERC721Receiver.onERC721Received.selector;
// Single token approval flag
// This bit is set in the owner's value to indicate that there is an approval set for this token
uint256 internal constant TOKEN_APPROVAL_OWNER_FLAG = 1 << 160;
// Burnt token magic value
// This magic number is used as the owner's value to indicate that the token has been burnt
uint256 internal constant BURNT_TOKEN_OWNER_VALUE = 0xdead000000000000000000000000000000000000000000000000000000000000;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/// @notice Marks the following ERC165 interface(s) as supported: ERC721.
function init() internal {
InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721).interfaceId, true);
}
/// @notice Marks the following ERC165 interface(s) as supported: ERC721BatchTransfer.
function initERC721BatchTransfer() internal {
InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721BatchTransfer).interfaceId, true);
}
/// @notice Marks the following ERC165 interface(s) as supported: ERC721Mintable.
function initERC721Mintable() internal {
InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Mintable).interfaceId, true);
}
/// @notice Marks the following ERC165 interface(s) as supported: ERC721Deliverable.
function initERC721Deliverable() internal {
InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Deliverable).interfaceId, true);
}
/// @notice Marks the following ERC165 interface(s) as supported: ERC721Burnable.
function initERC721Burnable() internal {
InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Burnable).interfaceId, true);
}
/// @notice Sets or unsets an approval to transfer a single token on behalf of its owner.
/// @dev Note: This function implements {ERC721-approve(address,uint256)}.
/// @dev Reverts if `tokenId` does not exist.
/// @dev Reverts if `to` is the token owner.
/// @dev Reverts if `sender` is not the token owner and has not been approved by the token owner.
/// @dev Emits an {Approval} event.
/// @param sender The message sender.
/// @param to The address to approve, or the zero address to remove any existing approval.
/// @param tokenId The token identifier to give approval for.
function approve(
Layout storage s,
address sender,
address to,
uint256 tokenId
) internal {
uint256 owner = s.owners[tokenId];
require(_tokenExists(owner), "ERC721: non-existing token");
address ownerAddress = _tokenOwner(owner);
require(to != ownerAddress, "ERC721: self-approval");
require(_isOperatable(s, ownerAddress, sender), "ERC721: non-approved sender");
if (to == address(0)) {
if (_tokenHasApproval(owner)) {
// remove the approval bit if it is present
s.owners[tokenId] = uint256(uint160(ownerAddress));
}
} else {
uint256 ownerWithApprovalBit = owner | TOKEN_APPROVAL_OWNER_FLAG;
if (owner != ownerWithApprovalBit) {
// add the approval bit if it is not present
s.owners[tokenId] = ownerWithApprovalBit;
}
s.approvals[tokenId] = to;
}
emit Approval(ownerAddress, to, tokenId);
}
/// @notice Sets or unsets an approval to transfer all tokens on behalf of their owner.
/// @dev Note: This function implements {ERC721-setApprovalForAll(address,bool)}.
/// @dev Reverts if `sender` is the same as `operator`.
/// @dev Emits an {ApprovalForAll} event.
/// @param sender The message sender.
/// @param operator The address to approve for all tokens.
/// @param approved True to set an approval for all tokens, false to unset it.
function setApprovalForAll(
Layout storage s,
address sender,
address operator,
bool approved
) internal {
require(operator != sender, "ERC721: self-approval for all");
s.operators[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @notice Unsafely transfers the ownership of a token to a recipient by a sender.
/// @dev Note: This function implements {ERC721-transferFrom(address,address,uint256)}.
/// @dev Resets the token approval for `tokenId`.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `from` is not the owner of `tokenId`.
/// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`.
/// @dev Emits a {Transfer} event.
/// @param sender The message sender.
/// @param from The current token owner.
/// @param to The recipient of the token transfer.
/// @param tokenId The identifier of the token to transfer.
function transferFrom(
Layout storage s,
address sender,
address from,
address to,
uint256 tokenId
) internal {
require(to != address(0), "ERC721: transfer to address(0)");
uint256 owner = s.owners[tokenId];
require(_tokenExists(owner), "ERC721: non-existing token");
require(_tokenOwner(owner) == from, "ERC721: non-owned token");
if (!_isOperatable(s, from, sender)) {
require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender");
}
s.owners[tokenId] = uint256(uint160(to));
if (from != to) {
unchecked {
// cannot underflow as balance is verified through ownership
--s.balances[from];
// cannot overflow as supply cannot overflow
++s.balances[to];
}
}
emit Transfer(from, to, tokenId);
}
/// @notice Safely transfers the ownership of a token to a recipient by a sender.
/// @dev Note: This function implements {ERC721-safeTransferFrom(address,address,uint256)}.
/// @dev Resets the token approval for `tokenId`.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `from` is not the owner of `tokenId`.
/// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`.
/// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected.
/// @dev Emits a {Transfer} event.
/// @param sender The message sender.
/// @param from The current token owner.
/// @param to The recipient of the token transfer.
/// @param tokenId The identifier of the token to transfer.
function safeTransferFrom(
Layout storage s,
address sender,
address from,
address to,
uint256 tokenId
) internal {
s.transferFrom(sender, from, to, tokenId);
if (to.isContract()) {
_callOnERC721Received(sender, from, to, tokenId, "");
}
}
/// @notice Safely transfers the ownership of a token to a recipient by a sender.
/// @dev Note: This function implements {ERC721-safeTransferFrom(address,address,uint256,bytes)}.
/// @dev Resets the token approval for `tokenId`.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `from` is not the owner of `tokenId`.
/// @dev Reverts if the sender is not `from` and has not been approved by `from` for `tokenId`.
/// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected.
/// @dev Emits a {Transfer} event.
/// @param sender The message sender.
/// @param from The current token owner.
/// @param to The recipient of the token transfer.
/// @param tokenId The identifier of the token to transfer.
/// @param data Optional data to send along to a receiver contract.
function safeTransferFrom(
Layout storage s,
address sender,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
s.transferFrom(sender, from, to, tokenId);
if (to.isContract()) {
_callOnERC721Received(sender, from, to, tokenId, data);
}
}
/// @notice Unsafely transfers a batch of tokens to a recipient by a sender.
/// @dev Note: This function implements {ERC721BatchTransfer-batchTransferFrom(address,address,uint256[])}.
/// @dev Resets the token approval for each of `tokenIds`.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if one of `tokenIds` is not owned by `from`.
/// @dev Reverts if the sender is not `from` and has not been approved by `from` for each of `tokenIds`.
/// @dev Emits a {Transfer} event for each of `tokenIds`.
/// @param sender The message sender.
/// @param from Current tokens owner.
/// @param to Address of the new token owner.
/// @param tokenIds Identifiers of the tokens to transfer.
function batchTransferFrom(
Layout storage s,
address sender,
address from,
address to,
uint256[] memory tokenIds
) internal {
require(to != address(0), "ERC721: transfer to address(0)");
bool operatable = _isOperatable(s, from, sender);
uint256 length = tokenIds.length;
unchecked {
for (uint256 i; i != length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 owner = s.owners[tokenId];
require(_tokenExists(owner), "ERC721: non-existing token");
require(_tokenOwner(owner) == from, "ERC721: non-owned token");
if (!operatable) {
require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender");
}
s.owners[tokenId] = uint256(uint160(to));
emit Transfer(from, to, tokenId);
}
if (from != to && length != 0) {
// cannot underflow as balance is verified through ownership
s.balances[from] -= length;
// cannot overflow as supply cannot overflow
s.balances[to] += length;
}
}
}
/// @notice Unsafely mints a token.
/// @dev Note: This function implements {ERC721Mintable-mint(address,uint256)}.
/// @dev Note: Either `mint` or `mintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `tokenId` already exists.
/// @dev Emits a {Transfer} event from the zero address.
/// @param to Address of the new token owner.
/// @param tokenId Identifier of the token to mint.
function mint(
Layout storage s,
address to,
uint256 tokenId
) internal {
require(to != address(0), "ERC721: mint to address(0)");
require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token");
s.owners[tokenId] = uint256(uint160(to));
unchecked {
// cannot overflow due to the cost of minting individual tokens
++s.balances[to];
}
emit Transfer(address(0), to, tokenId);
}
/// @notice Safely mints a token.
/// @dev Note: This function implements {ERC721Mintable-safeMint(address,uint256,bytes)}.
/// @dev Note: Either `safeMint` or `safeMintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `tokenId` already exists.
/// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected.
/// @dev Emits a {Transfer} event from the zero address.
/// @param to Address of the new token owner.
/// @param tokenId Identifier of the token to mint.
/// @param data Optional data to pass along to the receiver call.
function safeMint(
Layout storage s,
address sender,
address to,
uint256 tokenId,
bytes memory data
) internal {
s.mint(to, tokenId);
if (to.isContract()) {
_callOnERC721Received(sender, address(0), to, tokenId, data);
}
}
/// @notice Unsafely mints a batch of tokens.
/// @dev Note: This function implements {ERC721Mintable-batchMint(address,uint256[])}.
/// @dev Note: Either `batchMint` or `batchMintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if one of `tokenIds` already exists.
/// @dev Emits a {Transfer} event from the zero address for each of `tokenIds`.
/// @param to Address of the new tokens owner.
/// @param tokenIds Identifiers of the tokens to mint.
function batchMint(
Layout storage s,
address to,
uint256[] memory tokenIds
) internal {
require(to != address(0), "ERC721: mint to address(0)");
unchecked {
uint256 length = tokenIds.length;
for (uint256 i; i != length; ++i) {
uint256 tokenId = tokenIds[i];
require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token");
s.owners[tokenId] = uint256(uint160(to));
emit Transfer(address(0), to, tokenId);
}
s.balances[to] += length;
}
}
/// @notice Unsafely mints tokens to multiple recipients.
/// @dev Note: This function implements {ERC721Deliverable-deliver(address[],uint256[])}.
/// @dev Note: Either `deliver` or `deliverOnce` should be used in a given contract, but not both.
/// @dev Reverts if `recipients` and `tokenIds` have different lengths.
/// @dev Reverts if one of `recipients` is the zero address.
/// @dev Reverts if one of `tokenIds` already exists.
/// @dev Emits a {Transfer} event from the zero address for each of `recipients` and `tokenIds`.
/// @param recipients Addresses of the new tokens owners.
/// @param tokenIds Identifiers of the tokens to mint.
function deliver(
Layout storage s,
address[] memory recipients,
uint256[] memory tokenIds
) internal {
unchecked {
uint256 length = recipients.length;
require(length == tokenIds.length, "ERC721: inconsistent arrays");
for (uint256 i; i != length; ++i) {
address to = recipients[i];
require(to != address(0), "ERC721: mint to address(0)");
uint256 tokenId = tokenIds[i];
require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token");
s.owners[tokenId] = uint256(uint160(to));
++s.balances[to];
emit Transfer(address(0), to, tokenId);
}
}
}
/// @notice Unsafely mints a token once.
/// @dev Note: This function implements {ERC721Mintable-mint(address,uint256)}.
/// @dev Note: Either `mint` or `mintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `tokenId` already exists.
/// @dev Reverts if `tokenId` has been previously burnt.
/// @dev Emits a {Transfer} event from the zero address.
/// @param to Address of the new token owner.
/// @param tokenId Identifier of the token to mint.
function mintOnce(
Layout storage s,
address to,
uint256 tokenId
) internal {
require(to != address(0), "ERC721: mint to address(0)");
uint256 owner = s.owners[tokenId];
require(!_tokenExists(owner), "ERC721: existing token");
require(!_tokenWasBurnt(owner), "ERC721: burnt token");
s.owners[tokenId] = uint256(uint160(to));
unchecked {
// cannot overflow due to the cost of minting individual tokens
++s.balances[to];
}
emit Transfer(address(0), to, tokenId);
}
/// @notice Safely mints a token once.
/// @dev Note: This function implements {ERC721Mintable-safeMint(address,uint256,bytes)}.
/// @dev Note: Either `safeMint` or `safeMintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if `tokenId` already exists.
/// @dev Reverts if `tokenId` has been previously burnt.
/// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected.
/// @dev Emits a {Transfer} event from the zero address.
/// @param to Address of the new token owner.
/// @param tokenId Identifier of the token to mint.
/// @param data Optional data to pass along to the receiver call.
function safeMintOnce(
Layout storage s,
address sender,
address to,
uint256 tokenId,
bytes memory data
) internal {
s.mintOnce(to, tokenId);
if (to.isContract()) {
_callOnERC721Received(sender, address(0), to, tokenId, data);
}
}
/// @notice Unsafely mints a batch of tokens once.
/// @dev Note: This function implements {ERC721Mintable-batchMint(address,uint256[])}.
/// @dev Note: Either `batchMint` or `batchMintOnce` should be used in a given contract, but not both.
/// @dev Reverts if `to` is the zero address.
/// @dev Reverts if one of `tokenIds` already exists.
/// @dev Reverts if one of `tokenIds` has been previously burnt.
/// @dev Emits a {Transfer} event from the zero address for each of `tokenIds`.
/// @param to Address of the new tokens owner.
/// @param tokenIds Identifiers of the tokens to mint.
function batchMintOnce(
Layout storage s,
address to,
uint256[] memory tokenIds
) internal {
require(to != address(0), "ERC721: mint to address(0)");
unchecked {
uint256 length = tokenIds.length;
for (uint256 i; i != length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 owner = s.owners[tokenId];
require(!_tokenExists(owner), "ERC721: existing token");
require(!_tokenWasBurnt(owner), "ERC721: burnt token");
s.owners[tokenId] = uint256(uint160(to));
emit Transfer(address(0), to, tokenId);
}
s.balances[to] += length;
}
}
/// @notice Unsafely mints tokens to multiple recipients once.
/// @dev Note: This function implements {ERC721Deliverable-deliver(address[],uint256[])}.
/// @dev Note: Either `deliver` or `deliverOnce` should be used in a given contract, but not both.
/// @dev Reverts if `recipients` and `tokenIds` have different lengths.
/// @dev Reverts if one of `recipients` is the zero address.
/// @dev Reverts if one of `tokenIds` already exists.
/// @dev Reverts if one of `tokenIds` has been previously burnt.
/// @dev Emits a {Transfer} event from the zero address for each of `recipients` and `tokenIds`.
/// @param recipients Addresses of the new tokens owners.
/// @param tokenIds Identifiers of the tokens to mint.
function deliverOnce(
Layout storage s,
address[] memory recipients,
uint256[] memory tokenIds
) internal {
unchecked {
uint256 length = recipients.length;
require(length == tokenIds.length, "ERC721: inconsistent arrays");
for (uint256 i; i != length; ++i) {
address to = recipients[i];
require(to != address(0), "ERC721: mint to address(0)");
uint256 tokenId = tokenIds[i];
uint256 owner = s.owners[tokenId];
require(!_tokenExists(owner), "ERC721: existing token");
require(!_tokenWasBurnt(owner), "ERC721: burnt token");
s.owners[tokenId] = uint256(uint160(to));
++s.balances[to];
emit Transfer(address(0), to, tokenId);
}
}
}
/// @notice Burns a token by a sender.
/// @dev Note: This function implements {ERC721Burnable-burnFrom(address,uint256)}.
/// @dev Reverts if `tokenId` is not owned by `from`.
/// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`.
/// @dev Emits a {Transfer} event with `to` set to the zero address.
/// @param sender The message sender.
/// @param from The current token owner.
/// @param tokenId The identifier of the token to burn.
function burnFrom(
Layout storage s,
address sender,
address from,
uint256 tokenId
) internal {
uint256 owner = s.owners[tokenId];
require(from == _tokenOwner(owner), "ERC721: non-owned token");
if (!_isOperatable(s, from, sender)) {
require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender");
}
s.owners[tokenId] = BURNT_TOKEN_OWNER_VALUE;
unchecked {
// cannot underflow as balance is verified through TOKEN ownership
--s.balances[from];
}
emit Transfer(from, address(0), tokenId);
}
/// @notice Burns a batch of tokens by a sender.
/// @dev Note: This function implements {ERC721Burnable-batchBurnFrom(address,uint256[])}.
/// @dev Reverts if one of `tokenIds` is not owned by `from`.
/// @dev Reverts if `sender` is not `from` and has not been approved by `from` for each of `tokenIds`.
/// @dev Emits a {Transfer} event with `to` set to the zero address for each of `tokenIds`.
/// @param sender The message sender.
/// @param from The current tokens owner.
/// @param tokenIds The identifiers of the tokens to burn.
function batchBurnFrom(
Layout storage s,
address sender,
address from,
uint256[] memory tokenIds
) internal {
bool operatable = _isOperatable(s, from, sender);
unchecked {
uint256 length = tokenIds.length;
for (uint256 i; i != length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 owner = s.owners[tokenId];
require(from == _tokenOwner(owner), "ERC721: non-owned token");
if (!operatable) {
require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender");
}
s.owners[tokenId] = BURNT_TOKEN_OWNER_VALUE;
emit Transfer(from, address(0), tokenId);
}
if (length != 0) {
s.balances[from] -= length;
}
}
}
/// @notice Gets the balance of an address.
/// @dev Note: This function implements {ERC721-balanceOf(address)}.
/// @dev Reverts if `owner` is the zero address.
/// @param owner The address to query the balance of.
/// @return balance The amount owned by the owner.
function balanceOf(Layout storage s, address owner) internal view returns (uint256 balance) {
require(owner != address(0), "ERC721: balance of address(0)");
return s.balances[owner];
}
/// @notice Gets the owner of a token.
/// @dev Note: This function implements {ERC721-ownerOf(uint256)}.
/// @dev Reverts if `tokenId` does not exist.
/// @param tokenId The token identifier to query the owner of.
/// @return tokenOwner The owner of the token.
function ownerOf(Layout storage s, uint256 tokenId) internal view returns (address tokenOwner) {
uint256 owner = s.owners[tokenId];
require(_tokenExists(owner), "ERC721: non-existing token");
return _tokenOwner(owner);
}
/// @notice Gets the approved address for a token.
/// @dev Note: This function implements {ERC721-getApproved(uint256)}.
/// @dev Reverts if `tokenId` does not exist.
/// @param tokenId The token identifier to query the approval of.
/// @return approved The approved address for the token identifier, or the zero address if no approval is set.
function getApproved(Layout storage s, uint256 tokenId) internal view returns (address approved) {
uint256 owner = s.owners[tokenId];
require(_tokenExists(owner), "ERC721: non-existing token");
if (_tokenHasApproval(owner)) {
return s.approvals[tokenId];
} else {
return address(0);
}
}
/// @notice Gets whether an operator is approved for all tokens by an owner.
/// @dev Note: This function implements {ERC721-isApprovedForAll(address,address)}.
/// @param owner The address which gives the approval for all tokens.
/// @param operator The address which receives the approval for all tokens.
/// @return approvedForAll Whether the operator is approved for all tokens by the owner.
function isApprovedForAll(
Layout storage s,
address owner,
address operator
) internal view returns (bool approvedForAll) {
return s.operators[owner][operator];
}
/// @notice Gets whether a token was burnt.
/// @param tokenId The token identifier.
/// @return tokenWasBurnt Whether the token was burnt.
function wasBurnt(Layout storage s, uint256 tokenId) internal view returns (bool tokenWasBurnt) {
return _tokenWasBurnt(s.owners[tokenId]);
}
function layout() internal pure returns (Layout storage s) {
bytes32 position = LAYOUT_STORAGE_SLOT;
assembly {
s.slot := position
}
}
/// @notice Calls {IERC721Receiver-onERC721Received} on a target contract.
/// @dev Reverts if the call to the target fails, reverts or is rejected.
/// @param sender sender of the message.
/// @param from Previous token owner.
/// @param to New token owner.
/// @param tokenId Identifier of the token transferred.
/// @param data Optional data to send along with the receiver contract call.
function _callOnERC721Received(
address sender,
address from,
address to,
uint256 tokenId,
bytes memory data
) private {
require(IERC721Receiver(to).onERC721Received(sender, from, tokenId, data) == ERC721_RECEIVED, "ERC721: safe transfer rejected");
}
/// @notice Returns whether `sender` is authorised to make a transfer on behalf of `from`.
/// @param from The token owner.
/// @param sender The sender to check the operatability of.
/// @return operatable True if sender is `from` or an operator for `from`, false otherwise.
function _isOperatable(
Layout storage s,
address from,
address sender
) private view returns (bool operatable) {
return (from == sender) || s.operators[from][sender];
}
function _tokenOwner(uint256 owner) private pure returns (address tokenOwner) {
return address(uint160(owner));
}
function _tokenExists(uint256 owner) private pure returns (bool tokenExists) {
return uint160(owner) != 0;
}
function _tokenWasBurnt(uint256 owner) private pure returns (bool tokenWasBurnt) {
return owner == BURNT_TOKEN_OWNER_VALUE;
}
function _tokenHasApproval(uint256 owner) private pure returns (bool tokenSasApproval) {
return owner & TOKEN_APPROVAL_OWNER_FLAG != 0;
}
}
| Safely transfers the ownership of a token to a recipient by a sender. Note: This function implements {ERC721-safeTransferFrom(address,address,uint256,bytes)}. Resets the token approval for `tokenId`. Reverts if `to` is the zero address. Reverts if `from` is not the owner of `tokenId`. Reverts if the sender is not `from` and has not been approved by `from` for `tokenId`. Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. Emits a {Transfer} event. sender The message sender. from The current token owner. to The recipient of the token transfer. tokenId The identifier of the token to transfer. data Optional data to send along to a receiver contract. | function safeTransferFrom(
Layout storage s,
address sender,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
s.transferFrom(sender, from, to, tokenId);
if (to.isContract()) {
_callOnERC721Received(sender, from, to, tokenId, data);
}
}
| 15,845,394 |
./full_match/84531/0x575b832b9Be5660A372A56eB3375Ae2E72F9cfb5/sources/contracts/Soulbind.sol | Update an individual tokens metadata | function updateTokenURI(
uint256 tokenId,
bytes32 eventId,
string memory _tokenURI
) public validateOwnership(eventId) {
require(createdTokens[eventId].updatable, "Not updatable");
require(_exists(tokenId), "Invalid token");
_setTokenURI(tokenId, _tokenURI);
emit MetadataUpdate(tokenId);
}
| 14,293,800 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/StringUtils.sol";
import "./VanityNameRegistrar.sol";
import "./VanityNamePrices.sol";
contract VanityNameController is Ownable {
using StringUtils for *;
VanityNamePrices prices;
VanityNameRegistrar registrar;
// Amount that should be locked for every registration
uint256 private lockingAmount;
// Registration period
uint256 private registerPeriod;
// Sum of locked amount
uint256 public lockedAmountSum;
// List of commitments how it should be prevent front-run process
mapping(bytes32=>uint256) public commitments;
uint256 public minCommitmentAge;
uint256 public maxCommitmentAge;
struct LockingRecord {
uint256 amount; // How many locking amount the user has provided.
address owner; // User address that provides locking amount for some name
}
// For every tokenId how much amount is locked (if controller has changes about lock amount)
mapping(uint256=>LockingRecord) public lockingAmounts;
// Unlocked amounts per address
mapping(address=>uint256) public unlockedAmounts;
event NameRegistered(string name, bytes32 indexed label, address indexed owner, uint cost, uint expires);
event NameRenewed(string name, bytes32 indexed label, uint cost, uint expires);
event NewPrices(address indexed prices);
/**
* @dev Initializer for VanityNameController
* @param _prices Address for prices contract
* @param _registrar Address for registrar contract
* @param _lockingAmount Amount that should be locked for every registration
* @param _registerPeriod Registration period
* @param _minCommitmentAge Min commitment period
* @param _maxCommitmentAge Max commitment period
*/
constructor(VanityNamePrices _prices, VanityNameRegistrar _registrar,
uint256 _lockingAmount, uint256 _registerPeriod,
uint256 _minCommitmentAge, uint256 _maxCommitmentAge
) {
prices = _prices;
registrar = _registrar;
lockingAmount = _lockingAmount;
registerPeriod = _registerPeriod;
minCommitmentAge = _minCommitmentAge;
maxCommitmentAge = _maxCommitmentAge;
}
/**
* @dev Setter for locking variables
* @param _lockingAmount Amount that will be locked after register name
* @param _registerPeriod Period for how long will be name register
*/
function setLockingParameters(uint _lockingAmount, uint _registerPeriod) public onlyOwner {
lockingAmount = _lockingAmount;
registerPeriod = _registerPeriod;
}
/**
* @dev Setter for commitment ages
* @param _minCommitmentAge Min commitment period
* @param _maxCommitmentAge Max commitment period
*/
function setCommitmentAges(uint _minCommitmentAge, uint _maxCommitmentAge) public onlyOwner {
minCommitmentAge = _minCommitmentAge;
maxCommitmentAge = _maxCommitmentAge;
}
/**
* @dev Setter for prices contract
* @param _prices Prices contract
*/
function setPrices(VanityNamePrices _prices) public onlyOwner {
prices = _prices;
emit NewPrices(address(prices));
}
/**
* @dev Get price for specified name
* @param name Name for which it should be get price
*/
function rentPrice(string memory name) view public returns(uint) {
return prices.price(name);
}
/**
* @dev Get is name valid
* @param name Name that should be check is valid
*/
function valid(string memory name) public pure returns(bool) {
return name.strlen() >= 3;
}
/**
* @dev Check is specified name available
* @param name Name that should be check is available
*/
function available(string memory name) public view returns(bool) {
bytes32 label = keccak256(bytes(name));
return valid(name) && registrar.available(uint256(label));
}
/**
* @dev Make commitment how to prevent front-run
* @param name Name that should be check is available
* @param owner Owner for chosen name
* @param secret Secret value
*/
function makeCommitment(string memory name, address owner, bytes32 secret) pure public returns(bytes32) {
bytes32 label = keccak256(bytes(name));
return keccak256(abi.encodePacked(label, owner, secret));
}
/**
* @dev Commit chosen name, how no one could picked in maxCommitmentAge time
* @param commitment Name that should be check is available
*/
function commit(bytes32 commitment) public {
require(commitments[commitment] + maxCommitmentAge < block.timestamp, "VanityNameController: Max commitment age had passed");
commitments[commitment] = block.timestamp;
}
/**
* @dev Withdraw amounts that are payed for names
*/
function withdraw() public onlyOwner {
payable(msg.sender).transfer(address(this).balance - lockedAmountSum);
}
/**
* @dev Withdraw locked amount from expired name
* @param name Name for which should be withdraw lockedAmount + unlocked amounts from others tokens which are unlocked
*/
function unlockAndWithdrawAmount(string memory name) public {
bytes32 label = keccak256(bytes(name));
uint256 tokenId = uint256(label);
// Unlock amount for current tokenId (if it was from msg.sender and currently is available)
if (lockingAmounts[tokenId].owner == msg.sender && registrar.available(tokenId) == true) {
_unlockedAmount(tokenId);
}
withdrawUnlockedAmount();
}
/**
* @dev Withdraw locked amount that other users unlocked
*/
function withdrawUnlockedAmount() public {
uint256 amountForUnlock = unlockedAmounts[msg.sender];
unlockedAmounts[msg.sender] = 0;
payable(msg.sender).transfer(amountForUnlock);
}
/**
* @dev Register specified name on registerPeriod
* @param name Name that should be register
* @param owner Owner that register name
* @param secret Secret value
*/
function register(string memory name, address owner, bytes32 secret) public payable {
bytes32 commitment = makeCommitment(name, owner, secret);
uint cost = _consumeCommitment(name, commitment);
bytes32 label = keccak256(bytes(name));
uint256 tokenId = uint256(label);
// Return locking amount if user for this token still hasn't unlock amount
if (lockingAmounts[tokenId].amount > 0) {
_unlockedAmount(tokenId);
}
uint expires = registrar.register(tokenId, owner, registerPeriod);
lockingAmounts[tokenId].amount = lockingAmount;
lockingAmounts[tokenId].owner = owner;
lockedAmountSum = lockedAmountSum + lockingAmount;
emit NameRegistered(name, label, owner, cost, expires);
// Refund any extra payment
if(msg.value > cost + lockingAmount) {
payable(msg.sender).transfer(msg.value - cost - lockingAmount);
}
}
/**
* @dev Renew specified name on registerPeriod
* @param name Name that should be renew
*/
function renew(string calldata name) external payable {
uint cost = rentPrice(name);
require(msg.value >= cost, "VanityNameController: User doesn't send enough value");
bytes32 label = keccak256(bytes(name));
uint expires = registrar.renew(uint256(label), registerPeriod);
if(msg.value > cost) {
payable(msg.sender).transfer(msg.value - cost);
}
emit NameRenewed(name, label, cost, expires);
}
function _consumeCommitment(string memory name, bytes32 commitment) internal returns (uint256) {
// Require a valid commitment
require(commitments[commitment] + minCommitmentAge <= block.timestamp, "VanityNameController: Min commitment age isn't passed");
// If the commitment is too old, or the name is registered, stop
require(commitments[commitment] + maxCommitmentAge > block.timestamp, "VanityNameController: Max commitment age had passed");
require(available(name), "VanityNameController: Name is not available");
delete(commitments[commitment]);
uint cost = rentPrice(name);
require(msg.value >= cost + lockingAmount, "VanityNameController: User doesn't send enough value");
return cost;
}
function _unlockedAmount(uint256 tokenId) private {
// Get what amount should be unlocked and for what user
uint256 amountForUnlock = lockingAmounts[tokenId].amount;
address previousLockingAmountOwner = lockingAmounts[tokenId].owner;
if (amountForUnlock > 0 && previousLockingAmountOwner != address(0x0)) {
// Add unlocked amount to user which deposit amount
unlockedAmounts[previousLockingAmountOwner] = unlockedAmounts[previousLockingAmountOwner] + amountForUnlock;
lockingAmounts[tokenId].amount = 0;
lockingAmounts[tokenId].owner = address(0x0);
lockedAmountSum = lockedAmountSum - amountForUnlock;
}
}
} | Get what amount should be unlocked and for what user Add unlocked amount to user which deposit amount | function _unlockedAmount(uint256 tokenId) private {
uint256 amountForUnlock = lockingAmounts[tokenId].amount;
address previousLockingAmountOwner = lockingAmounts[tokenId].owner;
if (amountForUnlock > 0 && previousLockingAmountOwner != address(0x0)) {
unlockedAmounts[previousLockingAmountOwner] = unlockedAmounts[previousLockingAmountOwner] + amountForUnlock;
lockingAmounts[tokenId].amount = 0;
lockingAmounts[tokenId].owner = address(0x0);
lockedAmountSum = lockedAmountSum - amountForUnlock;
}
}
| 15,873,657 |
/**
*Submitted for verification at Etherscan.io on 2021-09-27
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/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;
// 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/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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 || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/TurtleTanks.sol
pragma solidity ^0.8.0;
/**
* @title TurtleTank contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract TurtleTanks is ERC721, ERC721Enumerable, Ownable {
string public PROVENANCE;
uint256 public tokenPrice = 30000000000000000; // 0.0005 ETH
uint256 public MAX_TOKENS = 10000;
uint public constant maxTokenPurchase = 10;
bool public saleIsActive = false;
string public _baseURIextended;
uint public teamreserve = 500;
uint public presaleTokens = 1000;
bool public presaleDone = false;
mapping(address => uint) private freeTokenMinted;
mapping(address => uint) private reserveInfluencer;
constructor() ERC721("Turtle Tanks", "TRLT") {
}
// CHANGED: needed to resolve conflicting fns in ERC721 and ERC721Enumerable
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
// CHANGED: needed to resolve conflicting fns in ERC721 and ERC721Enumerable
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
// CHANGED: added to account for changes in openzeppelin versions
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
// CHANGED: added to account for changes in openzeppelin versions
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function setProvenance(string memory provenance) public onlyOwner {
PROVENANCE = provenance;
}
// for both giveaway and team
function reserveTeam(address _to, uint256 _reserveAmount) public {
require(totalSupply() + _reserveAmount <= MAX_TOKENS, "Reserve would exceed max supply of tokens");
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= teamreserve, "Not enough reserve left for team");
teamreserve -= _reserveAmount; // max reserve for both team and influencers
if (totalSupply() + _reserveAmount >= presaleTokens && totalSupply() < presaleTokens && presaleDone == false){
saleIsActive = false;
presaleDone = true;
}
if (msg.sender != owner()){
require(reserveInfluencer[msg.sender] + _reserveAmount >= 0, "Not enough reserve left");
reserveInfluencer[msg.sender] -= _reserveAmount;
}
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
}
// set free mintable by influencer
function addInfluencer (address to, uint256 tokensToReserve) public onlyOwner{
reserveInfluencer[to] = tokensToReserve;
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function mint(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Tokens");
require(totalSupply() + numberOfTokens <= MAX_TOKENS, "Purchase would exceed max supply of tokens");
require(tokenPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
require(numberOfTokens <= maxTokenPurchase, "Exceeded max token purchase");
// Last tokens of presale -> stop presale
if (totalSupply() + numberOfTokens >= presaleTokens && totalSupply() < presaleTokens && presaleDone == false){
saleIsActive = false;
presaleDone = true;
}
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | for both giveaway and team | function reserveTeam(address _to, uint256 _reserveAmount) public {
require(totalSupply() + _reserveAmount <= MAX_TOKENS, "Reserve would exceed max supply of tokens");
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= teamreserve, "Not enough reserve left for team");
if (totalSupply() + _reserveAmount >= presaleTokens && totalSupply() < presaleTokens && presaleDone == false){
saleIsActive = false;
presaleDone = true;
}
if (msg.sender != owner()){
require(reserveInfluencer[msg.sender] + _reserveAmount >= 0, "Not enough reserve left");
reserveInfluencer[msg.sender] -= _reserveAmount;
}
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
}
| 2,436,197 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
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;
}
}
interface IToken {
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function burn(uint256 amount) external;
}
interface CudlFinance {
function claimMiningRewards(uint256 nftId) external;
function buyAccesory(uint256 nftId, uint256 id) external;
function itemPrice(uint256 itemId) external view returns (uint256);
function lastTimeMined(uint256 petId) external view returns (uint256);
}
interface IERC721 {
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
}
contract Lottery {
using SafeMath for uint256;
CudlFinance public immutable cudlFinance;
IToken public immutable cudl;
uint256 public food;
uint256 public nftOriginId;
mapping(uint256 => address[]) public players;
mapping(uint256 => mapping(address => uint256)) public ticketsByPlayers;
uint256 public currentPet = 0;
uint256 public currentRound = 0;
uint256 public end = 0;
uint256 public start = 0;
uint256 public randomBlockSize = 3;
address winner1;
address winner2;
address winner3;
address winner4;
address public owner;
// overflow
uint256 public MAX_INT = 2**256 - 1;
event LotteryStarted(
uint256 round,
uint256 start,
uint256 end,
uint256 petId,
uint256 foodId
);
event LotteryEnded(
uint256 round,
uint256 petId,
uint256 cudlPrize,
address winner1,
address winner2,
address winner3,
address winner4
);
event LotteryTicketBought(address participant, uint256 tickets);
constructor() public {
cudlFinance = CudlFinance(0x9c10AeD865b63f0A789ae64041581EAc63458209);
cudl = IToken(0xeCD20F0EBC3dA5E514b4454E3dc396E7dA18cA6A);
owner = msg.sender;
}
function startLottery(
uint256 _food,
uint256 _days,
uint256 _petId,
uint256 _nftOriginId
) external {
require(msg.sender == owner, "!owner");
food = _food;
currentRound = currentRound + 1;
end = now + _days * 1 days;
start = now;
cudl.approve(address(cudlFinance), MAX_INT);
currentPet = _petId;
nftOriginId = _nftOriginId;
emit LotteryStarted(currentRound, start, end, currentPet, food);
}
function getInfos(address player)
public
view
returns (
uint256 _participants,
uint256 _end,
uint256 _start,
uint256 _cudlSize,
uint256 _food,
uint256 _currentPet,
uint256 _foodPrice,
uint256 _ownerTickets,
uint256 _currentRound
)
{
_participants = players[currentRound].length;
_end = end;
_start = start;
_cudlSize = cudl.balanceOf(address(this));
_food = food;
_currentPet = currentPet;
_foodPrice = cudlFinance.itemPrice(food);
_ownerTickets = ticketsByPlayers[currentRound][player];
_currentRound = currentRound;
}
function buyTicket(address _player) external {
require(start != 0, "The lottery did not start yet");
if (now > end) {
endLottery();
return;
}
uint256 lastTimeMined = cudlFinance.lastTimeMined(currentPet);
uint8 tickets = 1;
require(
cudl.transferFrom(
msg.sender,
address(this),
cudlFinance.itemPrice(food)
)
);
cudlFinance.buyAccesory(currentPet, food);
// We mine if possible, the person that get the feeding transaction gets an extra ticket
if (lastTimeMined + 1 days < now) {
cudlFinance.claimMiningRewards(currentPet);
tickets = 2;
}
for (uint256 i = 0; i < tickets; i++) {
players[currentRound].push(_player);
ticketsByPlayers[currentRound][_player] =
ticketsByPlayers[currentRound][_player] +
1;
}
emit LotteryTicketBought(_player, tickets);
}
function endLottery() public {
require(now > end && end != 0);
uint256 cudlBalance = cudl.balanceOf(address(this));
end = 0;
start = 0;
// pick first winner (the vNFT)
winner1 = players[currentRound][
randomNumber(block.number, players[currentRound].length)
];
IERC721(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69).safeTransferFrom(
address(this),
winner1,
nftOriginId
);
// pick second winner (50% cudl)
winner2 = players[currentRound][
randomNumber(block.number - 1, players[currentRound].length)
];
require(cudl.transfer(winner2, cudlBalance.mul(37).div(100)));
// pick third winner (25% cudl)
winner3 = players[currentRound][
randomNumber(block.number - 3, players[currentRound].length)
];
require(cudl.transfer(winner3, cudlBalance.mul(19).div(100)));
// pick fourth winner (25% cudl)
winner4 = players[currentRound][
randomNumber(block.number - 4, players[currentRound].length)
];
require(cudl.transfer(winner4, cudlBalance.mul(19).div(100)));
//burn the leftover (25%)
cudl.burn(cudl.balanceOf(address(this)));
emit LotteryEnded(
currentRound,
currentPet,
cudlBalance,
winner1,
winner2,
winner3,
winner4
);
}
/* generates a number from 0 to 2^n based on the last n blocks */
function randomNumber(uint256 seed, uint256 max)
public
view
returns (uint256 _randomNumber)
{
uint256 n = 0;
for (uint256 i = 0; i < randomBlockSize; i++) {
if (
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - i - 1), seed)
)
) %
2 ==
0
) n += 2**i;
}
return n % max;
}
}
| We mine if possible, the person that get the feeding transaction gets an extra ticket | function buyTicket(address _player) external {
require(start != 0, "The lottery did not start yet");
if (now > end) {
endLottery();
return;
}
uint256 lastTimeMined = cudlFinance.lastTimeMined(currentPet);
uint8 tickets = 1;
require(
cudl.transferFrom(
msg.sender,
address(this),
cudlFinance.itemPrice(food)
)
);
cudlFinance.buyAccesory(currentPet, food);
if (lastTimeMined + 1 days < now) {
cudlFinance.claimMiningRewards(currentPet);
tickets = 2;
}
for (uint256 i = 0; i < tickets; i++) {
players[currentRound].push(_player);
ticketsByPlayers[currentRound][_player] =
ticketsByPlayers[currentRound][_player] +
1;
}
emit LotteryTicketBought(_player, tickets);
}
| 13,831,841 |
/**
*Submitted for verification at Etherscan.io on 2021-04-02
*/
pragma solidity ^0.8.2;
// SPDX-License-Identifier: MIT
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▀ ▀▓▌▐▓▓▓▓▓▀▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓ ▓▓▌▝▚▞▜▓ ▀▀ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▄▀▓▌▐▓▌▐▓▄▀▀▀▓▓▓▓▓▓▓▓▓▓▛▀▀▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▛▀▀▀▄▄▄▄▄▄▄▛▀▀▀▓▓▓▛▀▀▀▓▓▓▙▄▄▄▛▀▀▀▓▓▓▛▀▀▀▙▄▄▄▓▓▓▛▀▀▀▄▄▄▄▄▄▄▛▀▀▀▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▀▀▀▜▓▓▓▓▓▓▓▓▓▓▌ ▀▀▀▀▀▀▀▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓███ ▐███▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▀▀▀▀▀▀▀▓▓▓▓▓▓▓▌ ▓▓▓▛▀▀▀▙▄▄▄▓▓▓▙▄▄▄▛▀▀▀▓▓▓▓▓▓▓▀▀▀▀▀▀▀▀▀▀▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓ ▐▓▓▓▌ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓ ▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▌ ▓▓▓ ▐▓▓▓ ▐▓▓▓▓▌ ▓▓▓▓▓▓▓▓ ▐▓ ▐▓▓▓ ▐▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▙▄▄▄▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▌ ▐▓ ▐▓▓▓ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓ ▓▓▓▓ ▐▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓ ▐▓▓▓▓▓ ▐▓▓▓ ▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
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 ThePixelPortraits {
using SafeMath for uint256;
enum CommissionStatus { queued, accepted, removed }
struct Commission {
string name;
address payable recipient;
uint bid;
CommissionStatus status;
}
uint MAX_INT = uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
address payable public admin;
mapping (string => uint) public names;
mapping (uint => Commission) public commissions;
uint public minBid; // the number of wei required to create a commission
uint public newCommissionIndex; // the index of the next commission which should be created in the mapping
bool public callStarted; // ensures no re-entrancy can occur
modifier callNotStarted () {
require(!callStarted);
callStarted = true;
_;
callStarted = false;
}
modifier onlyAdmin {
require(msg.sender == admin, "not an admin");
_;
}
constructor(address payable _admin, uint _minBid) {
admin = _admin;
minBid = _minBid;
newCommissionIndex = 1;
}
function updateAdmin (address payable _newAdmin)
public
callNotStarted
onlyAdmin
{
admin = _newAdmin;
emit AdminUpdated(_newAdmin);
}
function updateMinBid (uint _newMinBid)
public
callNotStarted
onlyAdmin
{
minBid = _newMinBid;
emit MinBidUpdated(_newMinBid);
}
function registerNames (string[] memory _names)
public
callNotStarted
onlyAdmin
{
for (uint i = 0; i < _names.length; i++){
require(names[toLower(_names[i])] == 0, "name not available"); // ensures the name is not taken
names[toLower(_names[i])] = MAX_INT;
}
emit NamesRegistered(_names);
}
function commission (string memory _name)
public
callNotStarted
payable
{
require(validateName(_name), "name not valid"); // ensures the name is valid
require(names[toLower(_name)] == 0, "name not available"); // the name cannot be taken when you create your commission
require(msg.value >= minBid, "bid below minimum"); // must send the proper amount of into the bid
// Next, initialize the new commission
Commission storage newCommission = commissions[newCommissionIndex];
newCommission.name = _name;
newCommission.recipient = payable(msg.sender);
newCommission.bid = msg.value;
newCommission.status = CommissionStatus.queued;
emit NewCommission(newCommissionIndex, _name, msg.value, msg.sender);
newCommissionIndex++; // for the subsequent commission to be added into the next slot
}
function updateCommissionName (uint _commissionIndex, string memory _newName)
public
callNotStarted
{
require(_commissionIndex < newCommissionIndex, "commission not valid"); // must be a valid previously instantiated commission
Commission storage selectedCommission = commissions[_commissionIndex];
require(msg.sender == selectedCommission.recipient, "commission not yours"); // may only be performed by the person who commissioned it
require(selectedCommission.status == CommissionStatus.queued, "commission not in queue"); // the commission must still be queued
require(validateName(_newName), "name not valid"); // ensures the name is valid
require(names[toLower(_newName)] == 0, "name not available"); // the name cannot be taken when you create your commission
selectedCommission.name = _newName;
emit CommissionNameUpdated(_commissionIndex, _newName);
}
function rescindCommission (uint _commissionIndex)
public
callNotStarted
{
require(_commissionIndex < newCommissionIndex, "commission not valid"); // must be a valid previously instantiated commission
Commission storage selectedCommission = commissions[_commissionIndex];
require(msg.sender == selectedCommission.recipient, "commission not yours"); // may only be performed by the person who commissioned it
require(selectedCommission.status == CommissionStatus.queued, "commission not in queue"); // the commission must still be queued
// we mark it as removed and return the individual their bid
selectedCommission.status = CommissionStatus.removed;
selectedCommission.recipient.transfer(selectedCommission.bid);
emit CommissionRescinded(_commissionIndex);
}
function increaseCommissionBid (uint _commissionIndex)
public
payable
callNotStarted
{
require(_commissionIndex < newCommissionIndex, "commission not valid"); // must be a valid previously instantiated commission
Commission storage selectedCommission = commissions[_commissionIndex];
require(msg.sender == selectedCommission.recipient, "commission not yours"); // may only be performed by the person who commissioned it
require(selectedCommission.status == CommissionStatus.queued, "commission not in queue"); // the commission must still be queued
// then we update the commission's bid
selectedCommission.bid = msg.value + selectedCommission.bid;
emit CommissionBidUpdated(_commissionIndex, selectedCommission.bid);
}
function processCommissions(uint[] memory _commissionIndexes)
public
onlyAdmin
callNotStarted
{
for (uint i = 0; i < _commissionIndexes.length; i++){
Commission storage selectedCommission = commissions[_commissionIndexes[i]];
require(selectedCommission.status == CommissionStatus.queued, "commission not in the queue"); // the queue my not be empty when processing more commissions
require(names[toLower(selectedCommission.name)] == 0); // admins can't process commissions with names which are taken
// the name isn't taken yet and will be accepted
selectedCommission.status = CommissionStatus.accepted; // first, we change the status of the commission to accepted
names[toLower(selectedCommission.name)] = _commissionIndexes[i]; // finally, we reserve the name for this commission
admin.transfer(selectedCommission.bid); // next we accept the payment for the commission
emit CommissionProcessed(_commissionIndexes[i], selectedCommission.status);
}
}
// Credit to Hashmasks for the following functions
function validateName (string memory str)
public
pure
returns (bool)
{
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 25) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
function toLower (string memory str)
public
pure
returns (string memory)
{
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
event AdminUpdated(address _newAdmin);
event MinBidUpdated(uint _newMinBid);
event NamesRegistered(string[] _names);
event NewCommission(uint _commissionIndex, string _name, uint _bid, address _recipient);
event CommissionNameUpdated(uint _commissionIndex, string _newName);
event CommissionBidUpdated(uint _commissionIndex, uint _newBid);
event CommissionRescinded(uint _commissionIndex);
event CommissionProcessed(uint _commissionIndex, CommissionStatus _status);
} | the name isn't taken yet and will be accepted | function processCommissions(uint[] memory _commissionIndexes)
public
onlyAdmin
callNotStarted
{
for (uint i = 0; i < _commissionIndexes.length; i++){
Commission storage selectedCommission = commissions[_commissionIndexes[i]];
emit CommissionProcessed(_commissionIndexes[i], selectedCommission.status);
}
}
| 10,545,753 |
./partial_match/1/0x00000000Ede6d8D217c60f93191C060747324bca/sources/node_modules/@aperture_finance/uni-v3-lib/src/FullMath.sol | Returns the square root of a number. If the number is not a perfect square, the value is rounded down. | function sqrt(uint256 x) internal pure returns (uint256) {
return FixedPointMathLib.sqrt(x);
}
| 15,621,973 |
/*
Copyright 2019 Wanchain Foundation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
// Code style according to: https://github.com/wanchain/wanchain-token/blob/master/style-guide.rst
pragma solidity ^0.4.24;
import "../lib/SafeMath.sol";
import "../components/Admin.sol";
import "./GpkStorage.sol";
import "./lib/GpkLib.sol";
contract GpkDelegate is GpkStorage, Admin {
using SafeMath for uint;
/**
*
* EVENTS
*
*/
/// @notice event for storeman submit poly commit
/// @param groupId storeman group id
/// @param round group negotiate round
/// @param curveIndex signature curve index
/// @param storeman storeman address
event SetPolyCommitLogger(bytes32 indexed groupId, uint16 indexed round, uint8 indexed curveIndex, address storeman);
/// @notice event for storeman submit encoded sij
/// @param groupId storeman group id
/// @param round group negotiate round
/// @param curveIndex signature curve index
/// @param src src storeman address
/// @param dest dest storeman address
event SetEncSijLogger(bytes32 indexed groupId, uint16 indexed round, uint8 indexed curveIndex, address src, address dest);
/// @notice event for storeman submit result of checking encSij
/// @param groupId storeman group id
/// @param round group negotiate round
/// @param curveIndex signature curve index
/// @param src src storeman address
/// @param dest dest storeman address
/// @param isValid whether encSij is valid
event SetCheckStatusLogger(bytes32 indexed groupId, uint16 indexed round, uint8 indexed curveIndex, address src, address dest, bool isValid);
/// @notice event for storeman reveal sij
/// @param groupId storeman group id
/// @param round group negotiate round
/// @param curveIndex signature curve index
/// @param src src storeman address
/// @param dest dest storeman address
event RevealSijLogger(bytes32 indexed groupId, uint16 indexed round, uint8 indexed curveIndex, address src, address dest);
/**
*
* MANIPULATIONS
*
*/
/// @notice function for set smg contract address
/// @param cfgAddr cfg contract address
/// @param smgAddr smg contract address
function setDependence(address cfgAddr, address smgAddr)
external
onlyOwner
{
require(cfgAddr != address(0), "Invalid cfg");
cfg = cfgAddr;
require(smgAddr != address(0), "Invalid smg");
smg = smgAddr;
}
/// @notice function for set period
/// @param groupId group id
/// @param ployCommitPeriod ployCommit period
/// @param defaultPeriod default period
/// @param negotiatePeriod negotiate period
function setPeriod(bytes32 groupId, uint32 ployCommitPeriod, uint32 defaultPeriod, uint32 negotiatePeriod)
external
onlyAdmin
{
GpkTypes.Group storage group = groupMap[groupId];
group.ployCommitPeriod = ployCommitPeriod;
group.defaultPeriod = defaultPeriod;
group.negotiatePeriod = negotiatePeriod;
}
/// @notice function for storeman submit poly commit
/// @param groupId storeman group id
/// @param roundIndex group negotiate round
/// @param curveIndex singnature curve index
/// @param polyCommit poly commit list (17 order in x0,y0,x1,y1... format)
function setPolyCommit(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, bytes polyCommit)
external
{
require(polyCommit.length > 0, "Invalid polyCommit");
GpkTypes.Group storage group = groupMap[groupId];
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
if (group.smNumber == 0) {
// init group when the first node submit to start every round
GpkLib.initGroup(groupId, group, cfg, smg);
}
if (round.statusTime == 0) {
round.statusTime = now;
}
checkValid(group, roundIndex, curveIndex, GpkTypes.GpkStatus.PolyCommit, true, false, address(0));
require(round.srcMap[msg.sender].polyCommit.length == 0, "Duplicate");
round.srcMap[msg.sender].polyCommit = polyCommit;
round.polyCommitCount++;
GpkLib.updateGpk(round, polyCommit);
GpkLib.updateGpkShare(group, round, polyCommit);
if (round.polyCommitCount >= group.smNumber) {
round.status = GpkTypes.GpkStatus.Negotiate;
round.statusTime = now;
}
emit SetPolyCommitLogger(groupId, roundIndex, curveIndex, msg.sender);
}
/// @notice function for report storeman submit poly commit timeout
/// @param groupId storeman group id
/// @param curveIndex singnature curve index
function polyCommitTimeout(bytes32 groupId, uint8 curveIndex)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.PolyCommit, false, false, address(0));
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
uint32 timeout = (group.round == 0) ? group.ployCommitPeriod : group.defaultPeriod;
require(now.sub(round.statusTime) > timeout, "Not late");
uint slashCount = 0;
for (uint i = 0; (i < group.smNumber) && (slashCount + round.polyCommitCount < group.smNumber); i++) {
address src = group.addrMap[i];
if (round.srcMap[src].polyCommit.length == 0) {
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.PolyCommitTimeout, src, address(0), false, smg);
slashCount++;
}
}
GpkLib.slashMulti(group, curveIndex, smg);
}
/// @notice function for src storeman submit encSij
/// @param groupId storeman group id
/// @param roundIndex group negotiate round
/// @param curveIndex singnature curve index
/// @param dest dest storeman address
/// @param encSij encSij
function setEncSij(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address dest, bytes encSij)
external
{
require(encSij.length > 0, "Invalid encSij"); // ephemPublicKey(65) + iv(16) + mac(32) + ciphertext(48)
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, roundIndex, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, dest);
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
GpkTypes.Dest storage d = round.srcMap[msg.sender].destMap[dest];
require(d.encSij.length == 0, "Duplicate");
d.encSij = encSij;
d.setTime = now;
emit SetEncSijLogger(groupId, roundIndex, curveIndex, msg.sender, dest);
}
/// @notice function for dest storeman set check status for encSij
/// @param groupId storeman group id
/// @param roundIndex group negotiate round
/// @param curveIndex singnature curve index
/// @param src src storeman address
/// @param isValid whether encSij is valid
function setCheckStatus(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address src, bool isValid)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, roundIndex, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, src);
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
GpkTypes.Src storage s = round.srcMap[src];
GpkTypes.Dest storage d = s.destMap[msg.sender];
require(d.encSij.length != 0, "Not ready");
require(d.checkStatus == GpkTypes.CheckStatus.Init, "Duplicate");
d.checkTime = now;
emit SetCheckStatusLogger(groupId, roundIndex, curveIndex, src, msg.sender, isValid);
if (isValid) {
d.checkStatus = GpkTypes.CheckStatus.Valid;
s.checkValidCount++;
round.checkValidCount++;
if (round.checkValidCount >= group.smNumber ** 2) {
round.status = GpkTypes.GpkStatus.Complete;
round.statusTime = now;
GpkLib.tryComplete(group, smg);
}
} else {
d.checkStatus = GpkTypes.CheckStatus.Invalid;
}
}
/// @notice function for report src storeman submit encSij timeout
/// @param groupId storeman group id
/// @param curveIndex singnature curve index
/// @param src src storeman address
function encSijTimeout(bytes32 groupId, uint8 curveIndex, address src)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, src);
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
GpkTypes.Dest storage d = round.srcMap[src].destMap[msg.sender];
require(d.encSij.length == 0, "Outdated");
require(now.sub(round.statusTime) > group.defaultPeriod, "Not late");
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.EncSijTimout, src, msg.sender, true, smg);
}
/// @notice function for src storeman reveal sij
/// @param groupId storeman group id
/// @param roundIndex group negotiate round
/// @param curveIndex singnature curve index
/// @param dest dest storeman address
/// @param sij sij
/// @param ephemPrivateKey ecies ephemPrivateKey
function revealSij(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address dest, uint sij, uint ephemPrivateKey)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, roundIndex, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, dest);
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
GpkTypes.Src storage src = round.srcMap[msg.sender];
GpkTypes.Dest storage d = src.destMap[dest];
require(d.checkStatus == GpkTypes.CheckStatus.Invalid, "Not need");
d.sij = sij;
d.ephemPrivateKey = ephemPrivateKey;
emit RevealSijLogger(groupId, roundIndex, curveIndex, msg.sender, dest);
if (GpkLib.verifySij(d, group.pkMap[dest], src.polyCommit, round.curve)) {
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.CheckInvalid, dest, msg.sender, true, smg);
} else {
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.SijInvalid, msg.sender, dest, true, smg);
}
}
/// @notice function for report dest storeman check Sij timeout
/// @param groupId storeman group id
/// @param curveIndex singnature curve index
/// @param dest dest storeman address
function checkSijTimeout(bytes32 groupId, uint8 curveIndex, address dest)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, dest);
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
GpkTypes.Dest storage d = round.srcMap[msg.sender].destMap[dest];
require(d.checkStatus == GpkTypes.CheckStatus.Init, "Checked");
require(d.encSij.length != 0, "Not ready");
require(now.sub(d.setTime) > group.defaultPeriod, "Not late");
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.CheckTimeout, dest, msg.sender, true, smg);
}
/// @notice function for report srcPk submit sij timeout
/// @param groupId storeman group id
/// @param curveIndex singnature curve index
/// @param src src storeman address
function SijTimeout(bytes32 groupId, uint8 curveIndex, address src)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, src);
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
GpkTypes.Dest storage d = round.srcMap[src].destMap[msg.sender];
require(d.checkStatus == GpkTypes.CheckStatus.Invalid, "Not need");
require(now.sub(d.checkTime) > group.defaultPeriod, "Not late");
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.SijTimeout, src, msg.sender, true, smg);
}
/// @notice function for terminate protocol
/// @param groupId storeman group id
/// @param curveIndex singnature curve index
function terminate(bytes32 groupId, uint8 curveIndex)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.Negotiate, false, false, address(0));
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
require(now.sub(round.statusTime) > group.negotiatePeriod, "Not late");
for (uint i = 0; i < group.smNumber; i++) {
address src = group.addrMap[i];
uint slashPair = uint(group.smNumber).sub(uint(round.srcMap[src].checkValidCount));
for (uint j = 0; (j < group.smNumber) && (slashPair > 0); j++) {
address dest = group.addrMap[j];
GpkTypes.Dest storage d = round.srcMap[src].destMap[dest];
if (d.checkStatus != GpkTypes.CheckStatus.Valid) {
if (d.encSij.length == 0) {
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.EncSijTimout, src, dest, false, smg);
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.Connive, dest, src, false, smg);
} else if (d.checkStatus == GpkTypes.CheckStatus.Init) {
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.Connive, src, dest, false, smg);
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.CheckTimeout, dest, src, false, smg);
} else { // GpkTypes.CheckStatus.Invalid
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.SijTimeout, src, dest, false, smg);
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.Connive, dest, src, false, smg);
}
slashPair--;
}
}
}
GpkLib.slashMulti(group, curveIndex, smg);
}
/// @notice function for check paras
/// @param group group
/// @param roundIndex group negotiate round
/// @param curveIndex singnature curve index
/// @param status check group status
/// @param checkSender whether check msg.sender
/// @param checkStoreman whether check storeman
/// @param storeman storeman address
function checkValid(GpkTypes.Group storage group, uint16 roundIndex, uint8 curveIndex, GpkTypes.GpkStatus status, bool checkSender, bool checkStoreman, address storeman)
private
view
{
require(roundIndex == group.round, "Invalid round"); // must be current round
require(curveIndex <= 1, "Invalid curve"); // curve only can be 0 or 1
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
require((round.status == status) && (round.statusTime > 0), "Invalid status");
if (checkSender) {
require(group.pkMap[msg.sender].length > 0, "Invalid sender");
}
if (checkStoreman) {
require(group.pkMap[storeman].length > 0, "Invalid storeman");
}
}
function getGroupInfo(bytes32 groupId, int32 roundIndex)
external
view
returns(uint16 queriedRound, address curve1, uint8 curve1Status, uint curve1StatusTime, address curve2, uint8 curve2Status, uint curve2StatusTime)
{
GpkTypes.Group storage group = groupMap[groupId];
queriedRound = (roundIndex >= 0)? uint16(roundIndex) : group.round;
GpkTypes.Round storage round1 = group.roundMap[queriedRound][0];
GpkTypes.Round storage round2 = group.roundMap[queriedRound][1];
return (queriedRound, round1.curve, uint8(round1.status), round1.statusTime, round2.curve, uint8(round2.status), round2.statusTime);
}
function getPolyCommit(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address src)
external
view
returns(bytes polyCommit)
{
GpkTypes.Group storage group = groupMap[groupId];
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
return round.srcMap[src].polyCommit;
}
function getSijInfo(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address src, address dest)
external
view
returns(bytes encSij, uint8 checkStatus, uint setTime, uint checkTime, uint sij, uint ephemPrivateKey)
{
GpkTypes.Group storage group = groupMap[groupId];
GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex];
GpkTypes.Dest storage d = round.srcMap[src].destMap[dest];
return (d.encSij, uint8(d.checkStatus), d.setTime, d.checkTime, d.sij, d.ephemPrivateKey);
}
function getGpkShare(bytes32 groupId, uint16 index)
external
view
returns(bytes gpkShare1, bytes gpkShare2)
{
GpkTypes.Group storage group = groupMap[groupId];
address src = group.addrMap[index];
mapping(uint8 => GpkTypes.Round) roundMap = groupMap[groupId].roundMap[group.round];
return (roundMap[0].srcMap[src].gpkShare, roundMap[1].srcMap[src].gpkShare);
}
function getGpk(bytes32 groupId)
external
view
returns(bytes gpk1, bytes gpk2)
{
GpkTypes.Group storage group = groupMap[groupId];
mapping(uint8 => GpkTypes.Round) roundMap = groupMap[groupId].roundMap[group.round];
return (roundMap[0].gpk, roundMap[1].gpk);
}
/// @notice fallback function
function () public payable {
revert("Not support");
}
}
| function for report src storeman submit encSij timeout groupId storeman group id curveIndex singnature curve index src src storeman address | function encSijTimeout(bytes32 groupId, uint8 curveIndex, address src)
external
{
GpkTypes.Group storage group = groupMap[groupId];
checkValid(group, group.round, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, src);
GpkTypes.Round storage round = group.roundMap[group.round][curveIndex];
GpkTypes.Dest storage d = round.srcMap[src].destMap[msg.sender];
require(d.encSij.length == 0, "Outdated");
require(now.sub(round.statusTime) > group.defaultPeriod, "Not late");
GpkLib.slash(group, curveIndex, GpkTypes.SlashType.EncSijTimout, src, msg.sender, true, smg);
}
| 988,136 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV15Interface {
event Trade(
address account,
address suppliedAsset,
address receivedAsset,
address retainedAsset,
uint256 suppliedAmount,
uint256 recievedAmount,
uint256 retainedAmount
);
event RoleModified(Role indexed role, address account);
event RolePaused(Role indexed role);
event RoleUnpaused(Role indexed role);
event EtherReceived(address sender, uint256 amount);
event GasReserveRefilled(uint256 etherAmount);
event Withdrawal(
string indexed asset, address indexed primaryRecipient, uint256 amount
);
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER, // 4
GAS_RESERVE_REFILLER // 5
}
enum TradeType {
DAI_TO_TOKEN,
DAI_TO_ETH,
ETH_TO_DAI,
TOKEN_TO_DAI,
ETH_TO_TOKEN,
TOKEN_TO_ETH,
TOKEN_TO_TOKEN
}
struct RoleStatus {
address account;
bool paused;
}
function tradeDaiForEtherV2(
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeEtherForDaiV2(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought);
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold);
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function mint(uint256 daiAmount) external returns (uint256 dDaiMinted);
function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived);
function redeemUnderlying(
uint256 daiAmount
) external returns (uint256 dDaiSupplied);
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function tradeUSDCForDDai(
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function refillGasReserve(uint256 etherAmount) external;
function withdrawUSDC(address recipient, uint256 usdcAmount) external;
function withdrawDai(address recipient, uint256 daiAmount) external;
function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external;
function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawEtherToPrimaryRecipient(uint256 etherAmount) external;
function withdrawEther(
address payable recipient, uint256 etherAmount
) external;
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function callAny(
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function setDaiLimit(uint256 daiAmount) external;
function setEtherLimit(uint256 daiAmount) external;
function setPrimaryUSDCRecipient(address recipient) external;
function setPrimaryDaiRecipient(address recipient) external;
function setPrimaryEtherRecipient(address recipient) external;
function setRole(Role role, address account) external;
function removeRole(Role role) external;
function pause(Role role) external;
function unpause(Role role) external;
function isPaused(Role role) external view returns (bool paused);
function isRole(Role role) external view returns (bool hasRole);
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function getDepositManager() external view returns (address depositManager);
function getAdjuster() external view returns (address adjuster);
function getReserveTrader() external view returns (address reserveTrader);
function getWithdrawalManager() external view returns (
address withdrawalManager
);
function getPauser() external view returns (address pauser);
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
);
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
);
function getEtherLimit() external view returns (uint256 etherAmount);
function getPrimaryUSDCRecipient() external view returns (
address recipient
);
function getPrimaryDaiRecipient() external view returns (
address recipient
);
function getPrimaryEtherRecipient() external view returns (
address recipient
);
function getImplementation() external view returns (address implementation);
function getInstance() external pure returns (address instance);
function getVersion() external view returns (uint256 version);
}
interface ERC20Interface {
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function allowance(address, address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
interface DTokenInterface {
function redeem(
uint256 dTokensToBurn
) external returns (uint256 underlyingReceived);
function balanceOf(address) external view returns (uint256);
function balanceOfUnderlying(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function exchangeRateCurrent() external view returns (uint256);
}
interface DharmaDaiExchangerInterface {
function mintTo(
address account, uint256 daiToSupply
) external returns (uint256 dDaiMinted);
function redeemUnderlyingTo(
address account, uint256 daiToReceive
) external returns (uint256 dDaiBurned);
}
interface TradeHelperInterface {
function tradeUSDCForDDai(
uint256 amountUSDC,
uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function tradeDDaiForUSDC(
uint256 amountDai,
uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function getExpectedDai(uint256 usdc) external view returns (uint256 dai);
function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc);
}
interface UniswapV2Interface {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
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 swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function settleEther() external;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*
* In order to transfer ownership, a recipient must be specified, at which point
* the specified recipient can call `acceptOwnership` and take ownership.
*/
contract TwoStepOwnable {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
/**
* @dev Allows a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @dev Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() external onlyOwner {
delete _newPotentialOwner;
}
/**
* @dev Transfers ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() external {
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
/**
* @title DharmaTradeReserveV15ImplementationStaging
* @author 0age
* @notice This contract manages Dharma's reserves. It designates a collection
* of "roles" - these are dedicated accounts that can be modified by the owner,
* and that can trigger specific functionality on the reserve. These roles are:
* - depositManager (0): initiates Eth / token transfers to smart wallets
* - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai
* - withdrawalManager (2): initiates transfers to recipients set by the owner
* - reserveTrader (3): initiates trades using funds held in reserve
* - pauser (4): pauses any role (only the owner is then able to unpause it)
* - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve
*
* When finalizing deposits, the deposit manager must adhere to two constraints:
* - it must provide "proof" that the recipient is a smart wallet by including
* the initial user signing key used to derive the smart wallet address
* - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent
* value of Dharma Dai, than the current "limit" set by the owner.
*
* Note that "proofs" can be validated via `isSmartWallet`.
*/
contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable Dai transfer size for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable Ether transfer size for the deposit manager.
uint256 private _etherLimit;
bool private _unused; // unused, don't change storage layout
// Maintain a "primary recipient" where withdrawal manager can transfer Ether.
address private _primaryEtherRecipient;
uint256 private constant _VERSION = 1015;
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _USDC = ERC20Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _ETHERIZER = ERC20Interface(
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
DharmaDaiExchangerInterface internal constant _DDAI_EXCHANGER = (
DharmaDaiExchangerInterface(
0x83E02F0b169be417C38d1216fc2a5134C48Af44a
)
);
TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface(
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _ETH_RECEIVER = (
EtherReceiverInterface(
0xaf84687D21736F5E06f738c6F065e88890465E7c
)
);
address internal constant _WETH = address(
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
address internal constant _GAS_RESERVE = address(
0x09cd826D4ABA4088E1381A1957962C946520952d // staging version
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _CREATE2_HEADER = bytes21(
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000";
bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28(
0x00000000000000000000000000000000000000000000000000000000
);
string internal constant _TRANSFER_SIZE_EXCEEDED = string(
"Transfer size exceeds limit."
);
function initialize() external onlyOwner {
require(_DAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
require(_DDAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
}
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit EtherReceived(msg.sender, msg.value);
}
/**
* @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using
* UniswapV2, and return `quotedEtherAmount` Ether to the caller.
* @param daiAmount uint256 The Dai amount to supply when trading for Ether.
* @param quotedEtherAmount uint256 The amount of Ether to return to caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai sold as part of the trade.
*/
function tradeDaiForEtherV2(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiAmount, quotedEtherAmount, deadline, false
);
}
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiEquivalentAmount, quotedEtherAmount, deadline, false
);
}
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought) {
// Transfer the tokens from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade tokens for Ether.
totalEtherBought = _tradeTokenForEther(
token, tokenAmount, quotedEtherAmount, deadline, false
);
// Transfer the quoted Ether amount to the caller.
_transferEther(msg.sender, quotedEtherAmount);
}
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false
);
}
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token,
daiEquivalentAmount,
quotedTokenAmount,
deadline,
routeThroughEther,
false
);
}
/**
* @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed
* if necessary), trade for Ether using UniswapV2. Only the owner or the trade
* reserve role can call this function. Note that Dharma Dai will be redeemed
* to cover the Dai if there is not enough currently in the contract.
* @param daiAmountFromReserves the amount of Dai to take from reserves.
* @param quotedEtherAmount uint256 The Ether amount requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Ether bought as part of the trade.
*/
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for Ether using reserves.
totalDaiSold = _tradeDaiForEther(
daiAmountFromReserves, quotedEtherAmount, deadline, true
);
}
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalEtherBought
) {
// Trade tokens for Ether using reserves.
totalEtherBought = _tradeTokenForEther(
token, tokenAmountFromReserves, quotedEtherAmount, deadline, true
);
}
/**
* @notice Accept `msg.value` Ether from the caller, trade it for Dai using
* UniswapV2, and return `quotedDaiAmount` Dai to the caller.
* @param quotedDaiAmount uint256 The amount of Dai to return to the caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiV2(
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Transfer the Dai to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold) {
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, msg.value, quotedTokenAmount, deadline, false
);
}
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold) {
// Transfer the Ether from the caller and revert on failure.
_transferInToken(_ETHERIZER, msg.sender, etherAmount);
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, etherAmount, quotedTokenAmount, deadline, false
);
}
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Transfer the quoted Dai amount to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold) {
// Transfer the token from the caller and revert on failure.
_transferInToken(tokenProvided, msg.sender, tokenProvidedAmount);
totalTokensSold = _tradeTokenForToken(
msg.sender,
tokenProvided,
tokenReceived,
tokenProvidedAmount,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalTokensSold
) {
totalTokensSold = _tradeTokenForToken(
address(this),
tokenProvidedFromReserves,
tokenReceived,
tokenProvidedAmountFromReserves,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
/**
* @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2,
* and use that Dai to mint Dharma Dai.
* Only the owner or the trade reserve role can call this function.
* @param etherAmountFromReserves the amount of Ether to take from reserves
* and add to the provided amount.
* @param quotedDaiAmount uint256 The amount of Dai requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade Ether for Dai using reserves.
totalDaiBought = _tradeEtherForDai(
etherAmountFromReserves, quotedDaiAmount, deadline, true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) {
// Trade Ether for token using reserves.
totalEtherSold = _tradeEtherForToken(
token, etherAmountFromReserves, quotedTokenAmount, deadline, true
);
}
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for token using reserves.
totalDaiSold = _tradeDaiForToken(
token,
daiAmountFromReserves,
quotedTokenAmount,
deadline,
routeThroughEther,
true
);
}
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the token for Dai using reserves.
totalDaiBought = _tradeTokenForDai(
token,
tokenAmountFromReserves,
quotedDaiAmount,
deadline,
routeThroughEther,
true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
/**
* @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial
* user signing key `initialUserSigningKey` as proof that the specified smart
* wallet is indeed a Dharma Smart Wallet - this assumes that the address is
* derived and deployed using the Dharma Smart Wallet Factory V1. In addition,
* the specified amount must be less than the configured limit amount. Only
* the owner or the designated deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param daiAmount uint256 The amount of Dai to transfer - this must be less
* than the current limit.
*/
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Dai to the specified smart wallet.
_transferToken(_DAI, smartWallet, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Dai equivalent value of the specified dDai amount must
* be less than the configured limit amount. Only the owner or the designated
* deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai
* equivalent amount must be less than the current limit.
*/
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Get the current dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Invalid dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the dDai to the specified smart wallet.
_transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Ether amount must be less than the configured limit
* amount. Only the owner or the designated deposit manager role may call this
* function.
* @param smartWallet address The smart wallet to transfer Ether to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param etherAmount uint256 The amount of Ether to transfer - this amount
* must be less than the current limit.
*/
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Ether to the specified smart wallet.
_transferEther(smartWallet, etherAmount);
}
/**
* @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to supply when minting Dharma
* Dai.
* @return The amount of Dharma Dai minted.
*/
function mint(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _mintDDai(daiAmount, false);
}
/**
* @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the
* designated adjuster role may call this function.
* @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming
* for Dai.
* @return The amount of Dai received.
*/
function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _DDAI.redeem(dDaiAmount);
}
/**
* @notice Receive `daiAmount` Dai in exchange for Dharma Dai. Only the owner
* or the designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to receive when redeeming
* Dharma Dai.
* @return The amount of Dharma Dai supplied.
*/
function redeemUnderlying(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiSupplied) {
// Redeem the specified amount of dDai for Dai.
dDaiSupplied = _DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiAmount);
}
/**
* @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param usdcAmount uint256 The amount of USDC to supply when trading for
* Dharma Dai.
* @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value
* of the received dDai - this value is returned from the `getAndExpectedDai`
* view function on the trade helper.
* @return The amount of dDai received.
*/
function tradeUSDCForDDai(
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai(
usdcAmount, quotedDaiEquivalentAmount
);
}
/**
* @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in
* Dharma Dai for USDC. Only the owner or the designated adjuster role may
* call this function.
* @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in
* Dharma Dai when trading for USDC.
* @param quotedUSDCAmount uint256 The expected USDC received in exchange for
* dDai - this value is returned from the `getExpectedUSDC` view function on
* the trade helper.
* @return The amount of USDC received.
*/
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC(
daiEquivalentAmount, quotedUSDCAmount
);
}
function refillGasReserve(
uint256 etherAmount
) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) {
// Transfer the Ether to the gas reserve.
_transferEther(_GAS_RESERVE, etherAmount);
emit GasReserveRefilled(etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param usdcAmount uint256 The amount of USDC to transfer to the primary
* recipient.
*/
function withdrawUSDCToPrimaryRecipient(
uint256 usdcAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "USDC", usdcAmount
);
// Transfer the supplied USDC amount to the primary recipient.
_transferToken(_USDC, primaryRecipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param daiAmount uint256 The amount of Dai to transfer to the primary
* recipient.
*/
function withdrawDaiToPrimaryRecipient(
uint256 daiAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Dai", daiAmount
);
// Transfer the supplied Dai amount to the primary recipient.
_transferToken(_DAI, primaryRecipient, daiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to the current primary recipient set
* by the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param etherAmount uint256 The amount of Ether to transfer to the primary
* recipient.
*/
function withdrawEtherToPrimaryRecipient(
uint256 etherAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryEtherRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Ether", etherAmount
);
// Transfer the supplied Ether amount to the primary recipient.
_transferEther(primaryRecipient, etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer USDC to.
* @param usdcAmount uint256 The amount of USDC to transfer.
*/
function withdrawUSDC(
address recipient, uint256 usdcAmount
) external onlyOwner {
// Transfer the USDC to the specified recipient.
_transferToken(_USDC, recipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer Dai to.
* @param daiAmount uint256 The amount of Dai to transfer.
*/
function withdrawDai(
address recipient, uint256 daiAmount
) external onlyOwner {
// Transfer the Dai to the specified recipient.
_transferToken(_DAI, recipient, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Dharma Dai to.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer.
*/
function withdrawDharmaDai(
address recipient, uint256 dDaiAmount
) external onlyOwner {
// Transfer the dDai to the specified recipient.
_transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Ether to.
* @param etherAmount uint256 The amount of Ether to transfer.
*/
function withdrawEther(
address payable recipient, uint256 etherAmount
) external onlyOwner {
// Transfer the Ether to the specified recipient.
_transferEther(recipient, etherAmount);
}
/**
* @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the
* owner may call this function.
* @param token ERC20Interface The ERC20 token to transfer.
* @param recipient address The account to transfer the tokens to.
* @param amount uint256 The amount of tokens to transfer.
* @return A boolean to indicate if the transfer was successful - note that
* unsuccessful ERC20 transfers will usually revert.
*/
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external onlyOwner returns (bool success) {
// Transfer the token to the specified recipient.
success = token.transfer(recipient, amount);
}
/**
* @notice Call account `target`, supplying value `amount` and data `data`.
* Only the owner may call this function.
* @param target address The account to call.
* @param amount uint256 The amount of ether to include as an endowment.
* @param data bytes The data to include along with the call.
* @return A boolean to indicate if the call was successful, as well as the
* returned data or revert reason.
*/
function callAny(
address payable target, uint256 amount, bytes calldata data
) external onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
/**
* @notice Set `daiAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param daiAmount uint256 The new limit on the size of finalized deposits.
*/
function setDaiLimit(uint256 daiAmount) external onlyOwner {
// Set the new limit.
_daiLimit = daiAmount;
}
/**
* @notice Set `etherAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param etherAmount uint256 The new limit on the size of finalized deposits.
*/
function setEtherLimit(uint256 etherAmount) external onlyOwner {
// Set the new limit.
_etherLimit = etherAmount;
}
/**
* @notice Set `recipient` as the new primary recipient for USDC withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryUSDCRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Dai withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryDaiRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Ether withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryEtherRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryEtherRecipient = recipient;
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause.
*/
function pause(Role role) external onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause.
*/
function unpause(Role role) external onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for.
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from.
*/
function removeRole(Role role) external onlyOwner {
_setRole(role, address(0));
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on.
* @return A boolean to indicate if the functionality associated with the role
* in question is currently paused.
*/
function isPaused(Role role) external view returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check whether a "proof" that a given
* smart wallet is actually a Dharma Smart Wallet, based on the initial user
* signing key, is valid or not. This proof only works when the Dharma Smart
* Wallet in question is derived using V1 of the Dharma Smart Wallet Factory.
* @param smartWallet address The smart wallet to check.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @return A boolean indicating if the specified smart wallet account is
* indeed a smart wallet based on the specified initial user signing key.
*/
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey);
}
/**
* @notice External view function to check the account currently holding the
* deposit manager role. The deposit manager can process standard deposit
* finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but
* must prove that the recipient is a Dharma Smart Wallet and adhere to the
* current deposit size limit.
* @return The address of the current deposit manager, or the null address if
* none is set.
*/
function getDepositManager() external view returns (address depositManager) {
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and
* vice-versa via minting or redeeming.
* @return The address of the current adjuster, or the null address if none is
* set.
*/
function getAdjuster() external view returns (address adjuster) {
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
/**
* @notice External view function to check the account currently holding the
* reserve trader role. The reserve trader can trigger trades that utilize
* reserves in addition to supplied funds, if any.
* @return The address of the current reserve trader, or the null address if
* none is set.
*/
function getReserveTrader() external view returns (address reserveTrader) {
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
/**
* @notice External view function to check the account currently holding the
* withdrawal manager role. The withdrawal manager can transfer USDC, Dai, and
* Ether to their respective "primary recipient" accounts set by the owner.
* @return The address of the current withdrawal manager, or the null address
* if none is set.
*/
function getWithdrawalManager() external view returns (
address withdrawalManager
) {
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return The address of the current pauser, or the null address if none is
* set.
*/
function getPauser() external view returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
) {
gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account;
}
/**
* @notice External view function to check the current reserves held by this
* contract.
* @return The Dai and Dharma Dai reserves held by this contract, as well as
* the Dai-equivalent value of the Dharma Dai reserves.
*/
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _DAI.balanceOf(address(this));
dDai = _DDAI.balanceOf(address(this));
dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this));
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing deposits, expressed in Dai
* and in Dharma Dai.
* @return The Dai and Dharma Dai limit on deposit finalization amount.
*/
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent());
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing Ether deposits.
* @return The Ether limit on deposit finalization amount.
*/
function getEtherLimit() external view returns (uint256 etherAmount) {
etherAmount = _etherLimit;
}
/**
* @notice External view function to check the address of the current
* primary recipient for USDC.
* @return The primary recipient for USDC.
*/
function getPrimaryUSDCRecipient() external view returns (
address recipient
) {
recipient = _primaryUSDCRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Dai.
* @return The primary recipient for Dai.
*/
function getPrimaryDaiRecipient() external view returns (
address recipient
) {
recipient = _primaryDaiRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Ether.
* @return The primary recipient for Ether.
*/
function getPrimaryEtherRecipient() external view returns (
address recipient
) {
recipient = _primaryEtherRecipient;
}
/**
* @notice External view function to check the current implementation
* of this contract (i.e. the "logic" for the contract).
* @return The current implementation for this contract.
*/
function getImplementation() external view returns (
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
/**
* @notice External pure function to get the address of the actual
* contract instance (i.e. the "storage" foor this contract).
* @return The address of this contract instance.
*/
function getInstance() external pure returns (address instance) {
instance = address(0x2040F2f2bB228927235Dc24C33e99E3A0a7922c1);
}
function getVersion() external view returns (uint256 version) {
version = _VERSION;
}
function _grantUniswapRouterApprovalIfNecessary(
ERC20Interface token, uint256 amount
) internal {
if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) {
// Try removing router approval first as a workaround for unusual tokens.
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(0)
)
);
// Approve Uniswap router to transfer tokens on behalf of this contract.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1)
)
);
if (!success) {
// Some janky tokens only allow setting approval up to current balance.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), amount
)
);
}
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Uniswap router token approval failed."
);
}
}
function _tradeEtherForDai(
uint256 etherAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(_DAI), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_DAI,
address(0),
etherAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeDaiForEther(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), _WETH, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to correct recipient).
amounts = _UNISWAP_ROUTER.swapTokensForExactETH(
quotedEtherAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_ETH,
address(0),
daiAmount,
quotedEtherAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeEtherForToken(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(token), false
);
// Trade Ether for the quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)(
quotedTokenAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalEtherSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_TOKEN,
address(token),
etherAmount,
quotedTokenAmount,
etherAmount.sub(totalEtherSold)
);
}
function _tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), _WETH, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForETH(
tokenAmount, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_ETH,
address(token),
tokenAmount,
quotedEtherAmount,
totalEtherBought.sub(quotedEtherAmount)
);
}
function _tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), address(token), routeThroughEther
);
// Trade Dai for quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_TOKEN,
address(token),
daiAmount,
quotedTokenAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), address(_DAI), routeThroughEther
);
// Trade Dai for the quoted token amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenAmount, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[path.length - 1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_DAI,
address(token),
tokenAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeTokenForToken(
address recipient,
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) internal returns (uint256 totalTokensSold) {
uint256 retainedAmount;
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount);
if (routeThroughEther == false) {
// Establish direct path between tokens.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), tokenReceived, false
);
// Trade for the quoted token amount on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount,
tokenProvidedAmount,
path,
recipient,
deadline
);
totalTokensSold = amounts[0];
retainedAmount = tokenProvidedAmount.sub(totalTokensSold);
} else {
// Establish path between provided token and WETH.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), _WETH, false
);
// Trade all provided tokens for WETH on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenProvidedAmount, 0, path, address(this), deadline
);
retainedAmount = amounts[1];
// Establish path between WETH and received token.
(path, amounts) = _createPathAndAmounts(
_WETH, tokenReceived, false
);
// Trade bought WETH for received token on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline
);
totalTokensSold = amounts[0];
retainedAmount = retainedAmount.sub(totalTokensSold);
}
emit Trade(
recipient,
address(tokenProvided),
tokenReceived,
routeThroughEther ? _WETH : address(tokenProvided),
tokenProvidedAmount,
quotedTokenReceivedAmount,
retainedAmount
);
}
/**
* @notice Internal function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
function _fireTradeEvent(
bool fromReserves,
TradeType tradeType,
address token,
uint256 suppliedAmount,
uint256 receivedAmount,
uint256 retainedAmount
) internal {
uint256 t = uint256(tradeType);
emit Trade(
fromReserves ? address(this) : msg.sender,
t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token),
(t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)),
t < 4 ? address(_DAI) : address(0),
suppliedAmount,
receivedAmount,
retainedAmount
);
}
/**
* @notice Internal view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) internal view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Internal view function to check whether the given role is paused or
* not.
* @param role The role to check for.
* @return A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Internal view function to enforce that the given initial user
* signing key resolves to the given smart wallet when deployed through the
* Dharma Smart Wallet Factory V1. (staging version)
* @param smartWallet address The smart wallet.
* @param initialUserSigningKey address The initial user signing key.
*/
function _isSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_WALLET_CREATION_CODE_HEADER,
initialUserSigningKey,
_WALLET_CREATION_CODE_FOOTER
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_CREATE2_HEADER, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal {
uint256 daiBalance = _DAI.balanceOf(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), additionalDaiRequired);
}
}
function _transferToken(
ERC20Interface token, address to, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.transfer.selector, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer out failed.'
);
}
function _transferEther(address recipient, uint256 etherAmount) internal {
// Send quoted Ether amount to recipient and revert with reason on failure.
(bool ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _transferInToken(
ERC20Interface token, address from, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.transferFrom.selector, from, address(this), amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer in failed.'
);
}
function _mintDDai(
uint256 dai, bool sendToCaller
) internal returns (uint256 dDai) {
dDai = _DDAI_EXCHANGER.mintTo(
sendToCaller ? msg.sender : address(this), dai
);
}
function _transferAndRedeemDDai(
uint256 daiEquivalentAmount
) internal returns (uint256 totalDDaiRedeemed) {
// Determine dDai to redeem using exchange rate and daiEquivalentAmount.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
totalDDaiRedeemed = (
(daiEquivalentAmount.mul(1e18)).add(exchangeRate.sub(1)) // NOTE: round up
).div(exchangeRate);
// Transfer the dDai from the caller and revert on failure.
_transferInToken(
ERC20Interface(address(_DDAI)), msg.sender, totalDDaiRedeemed
);
// Redeem the dDai for Dai.
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiEquivalentAmount);
}
function _ensureSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure {
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Cannot resolve smart wallet using provided signing key."
);
}
function _createPathAndAmounts(
address start, address end, bool routeThroughEther
) internal pure returns (address[] memory, uint256[] memory) {
uint256 pathLength = routeThroughEther ? 3 : 2;
address[] memory path = new address[](pathLength);
path[0] = start;
if (routeThroughEther) {
path[1] = _WETH;
}
path[pathLength - 1] = end;
return (path, new uint256[](pathLength));
}
function _ensurePrimaryRecipientIsSetAndEmitEvent(
address primaryRecipient, string memory asset, uint256 amount
) internal {
if (primaryRecipient == address(0)) {
revert(string(abi.encodePacked(
asset, " does not have a primary recipient assigned."
)));
}
emit Withdrawal(asset, primaryRecipient, amount);
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner.
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
} | Establish path from Ether to target token. Trade Ether for the quoted token amount and send to correct recipient. | function _tradeEtherForToken(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherSold) {
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(token), false
);
amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)(
quotedTokenAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalEtherSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_TOKEN,
address(token),
etherAmount,
quotedTokenAmount,
etherAmount.sub(totalEtherSold)
);
}
| 6,603,040 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IController.sol";
import "./interfaces/IStrategy.sol";
/**
* @notice Base contract for vault.
*
* Vaults are capital pools of one single token which seaks yield from the market.
* A vault manages multiple strategies and at most one strategy is active at a time.
*
* The vault base is a function-complete standalone Yearn style vault. It does not prcess
* any rewards granted.
*/
contract VaultBase is ERC20Upgradeable, IVault {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
address public override token;
address public override controller;
address public override strategist;
mapping(address => bool) public override approvedStrategies;
address public override activeStrategy;
bool public override emergencyMode;
/**
* Add a lock to each address so that it could not perform deposit, withdraw, or transfer in the same block.
* Borrows ideas from Badger Sett.
* https://github.com/Badger-Finance/badger-system/blob/master/contracts/badger-sett/Sett.sol
*/
mapping(address => uint256) public lockBlocks;
uint256[50] private __gap;
event StrategistUpdated(address indexed oldStrategist, address indexed newStrategist);
event StrategyUpdated(address indexed strategy, bool indexed approved);
event ActiveStrategyUpdated(address indexed oldStrategy, address indexed newStrategy);
event EmergencyModeUpdated(bool indexed active);
event Deposited(address indexed user, address indexed token, uint256 amount, uint256 shareAmount);
event Withdrawn(address indexed user, address indexed token, uint256 amount, uint256 shareAmount);
/**
* @dev Initializes the Vault contract. Can be called only once.
* @param _token The token that the vault pools to seak return.
* @param _controller The Controller contract that manages the vaults.
* @param _nameOverride Provides a custom vault token name. Use default if empty.
* @param _symbolOverride Provides a custom vault token symbol. Use default if empty.
*/
function initialize(address _token, address _controller, string memory _nameOverride, string memory _symbolOverride) public virtual initializer {
require(_token != address(0x0), "want not set");
require(_controller != address(0x0), "controller not set");
token = _token;
controller = _controller;
strategist = msg.sender;
ERC20Upgradeable want = ERC20Upgradeable(_token);
string memory name;
string memory symbol;
if (bytes(_nameOverride).length > 0) {
name = _nameOverride;
} else {
name = string(abi.encodePacked(want.name(), " Vault"));
}
if (bytes(_symbolOverride).length > 0) {
symbol = _symbolOverride;
} else {
symbol = string(abi.encodePacked(want.symbol(), "v"));
}
__ERC20_init(name, symbol);
// The vault should have the same decimals as the want token.
_setupDecimals(want.decimals());
}
/**
* @dev Returns the governance of the vault.
* Note that Controller and all vaults share the same governance, so this is
* a shortcut to return Controller.governance().
*/
function governance() public view override returns (address) {
return IController(controller).governance();
}
modifier onlyGovernance() {
require(msg.sender == governance(), "not governance");
_;
}
modifier onlyStrategist() {
require(msg.sender == governance() || msg.sender == strategist, "not strategist");
_;
}
modifier notEmergencyMode() {
require(!emergencyMode, "emergency mode");
_;
}
/**
* @dev Checks whether the current block is locked for this address.
* A block is locked for an address if it performs deposit, withdraw or transfer in this block.
*/
modifier blockUnlocked() {
require(lockBlocks[msg.sender] < block.number, "block locked");
_;
}
function _updateLockBlock() internal {
lockBlocks[msg.sender] = block.number;
}
/**
* @dev Returns the total balance in both vault and strategy.
*/
function balance() public override view returns (uint256) {
IERC20Upgradeable want = IERC20Upgradeable(token);
return activeStrategy == address(0x0) ? want.balanceOf(address(this)) :
want.balanceOf(address(this)).add(IStrategy(activeStrategy).balanceOf());
}
/**
* @dev Updates the strategist address. Only governance or strategist can update strategist.
* Each vault has its own strategist to perform daily permissioned opertions.
* Vault and its strategies managed share the same strategist.
*/
function setStrategist(address _strategist) public override onlyStrategist {
address oldStrategist = strategist;
strategist = _strategist;
emit StrategistUpdated(oldStrategist, _strategist);
}
/**
* @dev Updates the emergency mode. Only governance or strategist can update emergency mode.
*/
function setEmergencyMode(bool _active) public override onlyStrategist {
emergencyMode = _active;
// If emergency mode is active and there is an active strategy,
// withdraws all assets from strategy back to the vault and resets active strategy.
address currentStrategy = activeStrategy;
if (_active && currentStrategy != address(0x0)) {
IStrategy(currentStrategy).withdrawAll();
activeStrategy = address(0x0);
emit ActiveStrategyUpdated(currentStrategy, address(0x0));
}
emit EmergencyModeUpdated(_active);
}
/**
* @dev Approves or revokes strategy. Only governance can approve or revoke strategies.
* Note that this does not affect the current active strategy and it takes effect only
* on the next time an active strategy is selected.
* @param _strategy Strategy to approve or revoke.
* @param _approved If true, the strategy can be selected as active strategy.
*/
function approveStrategy(address _strategy, bool _approved) public onlyGovernance {
approvedStrategies[_strategy] = _approved;
emit StrategyUpdated(_strategy, _approved);
}
/**
* @dev Updates the active strategy of the vault. Only governance or strategist can update the active strategy.
* Only approved strategy can be selected as active strategy.
* No new strategy is accepted in emergency mode.
*/
function setActiveStrategy(address _strategy) public override onlyStrategist notEmergencyMode {
// The new active strategy can be zero address, which means withdrawing all assets back to the vault.
// Otherwise, the new strategy must be approved by governance before hand.
require(_strategy == address(0x0) || approvedStrategies[_strategy], "strategy not approved");
address oldStrategy = activeStrategy;
require(oldStrategy != _strategy, "same strategy");
// If the vault has an existing strategy, withdraw all assets from it.
if (oldStrategy != address(0x0)) {
IStrategy(oldStrategy).withdrawAll();
}
activeStrategy = _strategy;
// Starts earning once a new strategy is set.
earn();
emit ActiveStrategyUpdated(oldStrategy, _strategy);
}
/**
* @dev Starts earning and deposits all current balance into strategy.
* Only strategist or governance can call this function.
* This function will throw if the vault is in emergency mode.
*/
function earn() public override onlyStrategist notEmergencyMode {
if (activeStrategy == address(0x0)) return;
IERC20Upgradeable want = IERC20Upgradeable(token);
uint256 _bal = want.balanceOf(address(this));
if (_bal > 0) {
want.safeTransfer(activeStrategy, _bal);
}
IStrategy(activeStrategy).deposit();
}
/**
* @dev Harvest yield from the strategy if set.
* Only strategist or governance can call this function.
* This function will throw if the vault is in emergency mode.
*/
function harvest() public override onlyStrategist notEmergencyMode {
require(activeStrategy != address(0x0), "no strategy");
IStrategy(activeStrategy).harvest();
}
/**
* @dev Deposit some balance to the vault.
* Deposit is not allowed when the vault is in emergency mode.
* If one deposit is completed, no new deposit/withdraw/transfer is allowed in the same block.
*/
function deposit(uint256 _amount) public virtual override notEmergencyMode blockUnlocked {
require(_amount > 0, "zero amount");
_updateLockBlock();
IERC20Upgradeable want = IERC20Upgradeable(token);
// If MAX is provided, deposits all balance.
if (_amount == uint256(-1)) {
_amount = want.balanceOf(msg.sender);
}
uint256 _pool = balance();
uint256 _before = want.balanceOf(address(this));
want.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = want.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
emit Deposited(msg.sender, address(want), _amount, shares);
}
/**
* @dev Withdraws some balance out of the vault.
* Withdraw is allowed even in emergency mode.
* If one withdraw is completed, no new deposit/withdraw/transfer is allowed in the same block.
*/
function withdraw(uint256 _shares) public virtual override blockUnlocked {
require(_shares > 0, "zero amount");
_updateLockBlock();
IERC20Upgradeable want = IERC20Upgradeable(token);
// If MAX is provided, withdraws all shares.
if (_shares == uint256(-1)) {
_shares = balanceOf(msg.sender);
}
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint256 b = want.balanceOf(address(this));
if (b < r) {
uint256 _withdraw = r.sub(b);
// Ideally this should not happen. Put here for extra safety.
require(activeStrategy != address(0x0), "no strategy");
IStrategy(activeStrategy).withdraw(_withdraw);
uint256 _after = want.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
r = b.add(_diff);
}
}
want.safeTransfer(msg.sender, r);
emit Withdrawn(msg.sender, address(want), r, _shares);
}
/**
* @dev Add lock to transfer so that it can not happen in the same block as deposit and withdraw.
*/
function transfer(address recipient, uint256 amount) public virtual override blockUnlocked returns (bool) {
return super.transfer(recipient, amount);
}
/**
* @dev Add lock to transfer so that it can not happen in the same block as deposit and withdraw.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override blockUnlocked returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/**
* @dev Used to salvage any ETH deposited into the vault by mistake.
* Only governance or strategist can salvage ETH from the vault.
* The salvaged ETH is transferred to treasury for futher operation.
*/
function salvage() public onlyStrategist {
uint256 amount = address(this).balance;
address payable target = payable(IController(controller).treasury());
(bool success, ) = target.call{value: amount}(new bytes(0));
require(success, 'ETH salvage failed');
}
/**
* @dev Used to salvage any token deposited into the vault by mistake.
* The want token cannot be salvaged.
* Only governance or strategist can salvage token from the vault.
* The salvaged token is transferred to treasury for futhuer operation.
* @param _tokenAddress Token address to salvage.
*/
function salvageToken(address _tokenAddress) public onlyStrategist {
require(_tokenAddress != token, "cannot salvage");
IERC20Upgradeable target = IERC20Upgradeable(_tokenAddress);
target.safeTransfer(IController(controller).treasury(), target.balanceOf(address(this)));
}
/**
* @dev Returns the number of vault token per share is worth.
*/
function getPricePerFullShare() public override view returns (uint256) {
if (totalSupply() == 0) return 0;
return balance().mul(1e18).div(totalSupply());
}
function exit() public virtual override {
withdraw(uint256(-1));
}
function claimReward() public virtual override returns (uint256) {
revert("reward is not supported");
}
function notifyRewardAmount(uint256) public virtual override {
revert("reward is not supported");
}
function addRewards(uint256) public virtual override {
revert("reward is not supported");
}
}
| Updates the strategist address. Only governance or strategist can update strategist. Each vault has its own strategist to perform daily permissioned opertions. Vault and its strategies managed share the same strategist./ | function setStrategist(address _strategist) public override onlyStrategist {
address oldStrategist = strategist;
strategist = _strategist;
emit StrategistUpdated(oldStrategist, _strategist);
}
| 2,491,744 |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./CompoundInteractor.sol";
import "./CompleteCToken.sol";
import "../LiquidityRecipient.sol";
import "../../Controllable.sol";
import "../RewardTokenProfitNotifier.sol";
import "../../compound/ComptrollerInterface.sol";
import "../../compound/CTokenInterfaces.sol";
import "../../hardworkInterface/IStrategy.sol";
import "../../uniswap/interfaces/IUniswapV2Router02.sol";
import "../../hardworkInterface/IVault.sol";
contract CompoundWETHFoldStrategy is IStrategy, RewardTokenProfitNotifier, CompoundInteractor {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitNotClaimed();
event TooLowBalance();
ERC20Detailed public underlying;
CompleteCToken public ctoken;
ComptrollerInterface public comptroller;
address public vault;
ERC20Detailed public comp; // this will be Cream or Comp
address public uniswapRouterV2;
uint256 public suppliedInUnderlying;
uint256 public borrowedInUnderlying;
bool public liquidationAllowed = true;
uint256 public sellFloor = 0;
bool public allowEmergencyLiquidityShortage = false;
uint256 public collateralFactorNumerator = 100;
uint256 public collateralFactorDenominator = 1000;
uint256 public folds = 0;
// The strategy supplying liquidity to Uniswap
address public liquidityRecipient;
// The current loan
uint256 public liquidityLoanCurrent;
// The target loan
uint256 public liquidityLoanTarget;
uint256 public constant tenWeth = 10 * 1e18;
uint256 public borrowMinThreshold = 0;
// These tokens cannot be claimed by the controller
mapping(address => bool) public unsalvagableTokens;
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault");
_;
}
event Liquidated(
uint256 amount
);
constructor(
address _storage,
address _underlying,
address _ctoken,
address _vault,
address _comptroller,
address _comp,
address _uniswap
)
RewardTokenProfitNotifier(_storage, _comp)
CompoundInteractor(_underlying, _ctoken, _comptroller) public {
require(IVault(_vault).underlying() == _underlying, "vault does not support underlying");
comptroller = ComptrollerInterface(_comptroller);
comp = ERC20Detailed(_comp);
underlying = ERC20Detailed(_underlying);
ctoken = CompleteCToken(_ctoken);
vault = _vault;
uniswapRouterV2 = _uniswap;
// set these tokens to be not salvagable
unsalvagableTokens[_underlying] = true;
unsalvagableTokens[_ctoken] = true;
unsalvagableTokens[_comp] = true;
}
modifier updateSupplyInTheEnd() {
_;
suppliedInUnderlying = ctoken.balanceOfUnderlying(address(this));
borrowedInUnderlying = ctoken.borrowBalanceCurrent(address(this));
}
function depositArbCheck() public view returns (bool) {
// there's no arb here.
return true;
}
/**
* The strategy invests by supplying the underlying as a collateral.
*/
function investAllUnderlying() public restricted updateSupplyInTheEnd {
uint256 balance = underlying.balanceOf(address(this));
_supplyEtherInWETH(balance);
for (uint256 i = 0; i < folds; i++) {
uint256 borrowAmount = balance.mul(collateralFactorNumerator).div(collateralFactorDenominator);
_borrowInWETH(borrowAmount);
balance = underlying.balanceOf(address(this));
_supplyEtherInWETH(balance);
}
}
/**
* Exits Compound and transfers everything to the vault.
*/
function withdrawAllToVault() external restricted updateSupplyInTheEnd {
if (allowEmergencyLiquidityShortage) {
withdrawMaximum();
} else {
withdrawAllWeInvested();
}
if (underlying.balanceOf(address(this)) > 0) {
IERC20(address(underlying)).safeTransfer(vault, underlying.balanceOf(address(this)));
}
}
function emergencyExit() external onlyGovernance updateSupplyInTheEnd {
withdrawMaximum();
}
function withdrawMaximum() internal updateSupplyInTheEnd {
if (liquidationAllowed) {
claimComp();
liquidateComp();
} else {
emit ProfitNotClaimed();
}
redeemMaximum();
}
function withdrawAllWeInvested() internal updateSupplyInTheEnd {
require(liquidityLoanCurrent == 0, "Liquidity loan must be settled first");
if (liquidationAllowed) {
claimComp();
liquidateComp();
} else {
emit ProfitNotClaimed();
}
uint256 _currentSuppliedBalance = ctoken.balanceOfUnderlying(address(this));
uint256 _currentBorrowedBalance = ctoken.borrowBalanceCurrent(address(this));
mustRedeemPartial(_currentSuppliedBalance.sub(_currentBorrowedBalance));
}
function withdrawToVault(uint256 amountUnderlying) external restricted updateSupplyInTheEnd {
if (amountUnderlying <= underlying.balanceOf(address(this))) {
IERC20(address(underlying)).safeTransfer(vault, amountUnderlying);
return;
}
// get some of the underlying
mustRedeemPartial(amountUnderlying);
// transfer the amount requested (or the amount we have) back to vault
IERC20(address(underlying)).safeTransfer(vault, amountUnderlying);
// invest back to compound
investAllUnderlying();
}
/**
* Withdraws all assets, liquidates COMP/CREAM, and invests again in the required ratio.
*/
function doHardWork() public restricted {
if (liquidationAllowed) {
claimComp();
liquidateComp();
} else {
emit ProfitNotClaimed();
}
investAllUnderlying();
}
/**
* Redeems maximum that can be redeemed from Compound.
* Redeem the minimum of the underlying we own, and the underlying that the cToken can
* immediately retrieve. Ensures that `redeemMaximum` doesn't fail silently.
*
* DOES NOT ensure that the strategy cUnderlying balance becomes 0.
*/
function redeemMaximum() internal {
redeemMaximumWethWithLoan(
collateralFactorNumerator,
collateralFactorDenominator,
borrowMinThreshold
);
}
/**
* Redeems `amountUnderlying` or fails.
*/
function mustRedeemPartial(uint256 amountUnderlying) internal {
require(
ctoken.getCash() >= amountUnderlying,
"market cash cannot cover liquidity"
);
redeemMaximum();
require(underlying.balanceOf(address(this)) >= amountUnderlying, "Unable to withdraw the entire amountUnderlying");
}
/**
* Salvages a token.
*/
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvagable");
IERC20(token).safeTransfer(recipient, amount);
}
function liquidateComp() internal {
uint256 balance = comp.balanceOf(address(this));
if (balance < sellFloor || balance == 0) {
emit TooLowBalance();
return;
}
// give a profit share to fee forwarder, which re-distributes this to
// the profit sharing pools
notifyProfitInRewardToken(balance);
balance = comp.balanceOf(address(this));
emit Liquidated(balance);
// we can accept 1 as minimum as this will be called by trusted roles only
uint256 amountOutMin = 1;
IERC20(address(comp)).safeApprove(address(uniswapRouterV2), 0);
IERC20(address(comp)).safeApprove(address(uniswapRouterV2), balance);
address[] memory path = new address[](2);
path[0] = address(comp);
path[1] = address(underlying);
uint256 wethBefore = underlying.balanceOf(address(this));
IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens(
balance,
amountOutMin,
path,
address(this),
block.timestamp
);
}
/**
* Returns the current balance. Ignores COMP/CREAM that was not liquidated and invested.
*/
function investedUnderlyingBalance() public view returns (uint256) {
// underlying in this strategy + underlying redeemable from Compound/Cream + loan
return underlying.balanceOf(address(this))
.add(suppliedInUnderlying)
.sub(borrowedInUnderlying)
.add(liquidityLoanCurrent);
}
/**
* Allows liquidation
*/
function setLiquidationAllowed(
bool allowed
) external restricted {
liquidationAllowed = allowed;
}
function setAllowLiquidityShortage(
bool allowed
) external restricted {
allowEmergencyLiquidityShortage = allowed;
}
function setSellFloor(uint256 value) external restricted {
sellFloor = value;
}
/**
* Provides a loan to the liquidity strategy. Sends in funds to fill out the loan target amount,
* if they are available.
*/
function provideLoan() public onlyGovernance updateSupplyInTheEnd {
withdrawMaximum();
if (liquidityLoanCurrent < liquidityLoanTarget
&& IERC20(underlying).balanceOf(address(this)) > 0
&& liquidityRecipient != address(0)
) {
uint256 diff = Math.min(
liquidityLoanTarget.sub(liquidityLoanCurrent),
IERC20(underlying).balanceOf(address(this))
);
IERC20(underlying).safeApprove(liquidityRecipient, 0);
IERC20(underlying).safeApprove(liquidityRecipient, diff);
// use the pull pattern so that this fails if the contract is not set properly
LiquidityRecipient(liquidityRecipient).takeLoan(diff);
liquidityLoanCurrent = liquidityLoanCurrent.add(diff);
}
investAllUnderlying();
}
/**
* Settles a loan amount by forcing withdrawal inside the liquidity strategy, and then transferring
* the funds back to this strategy. This way, the loan can be settled partially, or completely.
* The method can be invoked only by EOAs to avoid market manipulation, and only by the governance
* unless there is not more than 10 WETH left in this strategy.
*/
function settleLoan(uint256 amount) public updateSupplyInTheEnd {
require(
// the only funds in are in the loan, other than 10 WETH
investedUnderlyingBalance() <= liquidityLoanCurrent.add(tenWeth)
// or the governance wants this to happen
|| msg.sender == governance(),
"Buffer exists and the caller is not governance"
);
// market manipulation prevention
require(tx.origin == msg.sender, "no smart contracts");
if (liquidityLoanCurrent == 0) {
return;
}
LiquidityRecipient(liquidityRecipient).settleLoan();
IERC20(underlying).safeTransferFrom(liquidityRecipient, address(this), amount);
liquidityLoanCurrent = liquidityLoanCurrent.sub(amount);
if (liquidityLoanCurrent == 0) {
LiquidityRecipient(liquidityRecipient).wethOverdraft();
}
}
function setLiquidityRecipient(address recipient) public onlyGovernance {
require(liquidityRecipient == address(0) || liquidityLoanCurrent == 0,
"Liquidity recipient was already set, and has a loan");
liquidityRecipient = recipient;
}
function setBorrowMinThreshold(uint256 threshold) public onlyGovernance {
borrowMinThreshold = threshold;
}
// updating collateral factor
// note 1: one should settle the loan first before calling this
// note 2: collateralFactorDenominator is 1000, therefore, for 20%, you need 200
function setCollateralFactorNumerator(uint256 numerator) public onlyGovernance {
require(numerator <= 740, "Collateral factor cannot be this high");
collateralFactorNumerator = numerator;
}
function setLiquidityLoanTarget(uint256 target) public onlyGovernance {
liquidityLoanTarget = target;
}
function setFolds(uint256 _folds) public onlyGovernance {
folds = _folds;
}
}
| The strategy invests by supplying the underlying as a collateral./ | function investAllUnderlying() public restricted updateSupplyInTheEnd {
uint256 balance = underlying.balanceOf(address(this));
_supplyEtherInWETH(balance);
for (uint256 i = 0; i < folds; i++) {
uint256 borrowAmount = balance.mul(collateralFactorNumerator).div(collateralFactorDenominator);
_borrowInWETH(borrowAmount);
balance = underlying.balanceOf(address(this));
_supplyEtherInWETH(balance);
}
}
| 998,631 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/ReentrancyGuard.sol";
import "./markets/MarketRegistry.sol";
import "./SpecialTransferHelper.sol";
import "../../interfaces/markets/tokens/IERC20.sol";
import "../../interfaces/markets/tokens/IERC721.sol";
import "../../interfaces/markets/tokens/IERC1155.sol";
contract GemSwap is SpecialTransferHelper, Ownable, ReentrancyGuard {
struct OpenseaTrades {
uint256 value;
bytes tradeData;
}
struct ERC20Details {
address[] tokenAddrs;
uint256[] amounts;
}
struct ERC1155Details {
address tokenAddr;
uint256[] ids;
uint256[] amounts;
}
struct ConverstionDetails {
bytes conversionData;
}
struct AffiliateDetails {
address affiliate;
bool isActive;
}
struct SponsoredMarket {
uint256 marketId;
bool isActive;
}
address public constant GOV = 0x83d841bC0450D5Ac35DCAd8d05Db53EbA29978c2;
address public guardian;
address public converter;
address public punkProxy;
uint256 public baseFees;
bool public openForTrades;
bool public openForFreeTrades;
MarketRegistry public marketRegistry;
AffiliateDetails[] public affiliates;
SponsoredMarket[] public sponsoredMarkets;
modifier isOpenForTrades() {
require(openForTrades, "trades not allowed");
_;
}
modifier isOpenForFreeTrades() {
require(openForFreeTrades, "free trades not allowed");
_;
}
constructor(address _marketRegistry, address _converter, address _guardian) {
marketRegistry = MarketRegistry(_marketRegistry);
converter = _converter;
guardian = _guardian;
baseFees = 0;
openForTrades = true;
openForFreeTrades = true;
affiliates.push(AffiliateDetails(GOV, true));
}
function setUp() external onlyOwner {
// Create CryptoPunk Proxy
IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).registerProxy();
punkProxy = IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).proxyInfo(address(this));
// approve wrapped mooncats rescue to AcclimatedMoonCats contract
IERC721(0x7C40c393DC0f283F318791d746d894DdD3693572).setApprovalForAll(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, true);
}
// @audit This function is used to approve specific tokens to specific market contracts with high volume.
// This is done in very rare cases for the gas optimization purposes.
function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner {
token.approve(operator, amount);
}
function updateGuardian(address _guardian) external onlyOwner {
guardian = _guardian;
}
function addAffiliate(address _affiliate) external onlyOwner {
affiliates.push(AffiliateDetails(_affiliate, true));
}
function updateAffiliate(uint256 _affiliateIndex, address _affiliate, bool _IsActive) external onlyOwner {
affiliates[_affiliateIndex] = AffiliateDetails(_affiliate, _IsActive);
}
function addSponsoredMarket(uint256 _marketId) external onlyOwner {
sponsoredMarkets.push(SponsoredMarket(_marketId, true));
}
function updateSponsoredMarket(uint256 _marketIndex, uint256 _marketId, bool _isActive) external onlyOwner {
sponsoredMarkets[_marketIndex] = SponsoredMarket(_marketId, _isActive);
}
function setBaseFees(uint256 _baseFees) external onlyOwner {
baseFees = _baseFees;
}
function setOpenForTrades(bool _openForTrades) external onlyOwner {
openForTrades = _openForTrades;
}
function setOpenForFreeTrades(bool _openForFreeTrades) external onlyOwner {
openForFreeTrades = _openForFreeTrades;
}
// @audit we will setup a system that will monitor the contract for any leftover
// assets. In case any asset is leftover, the system should be able to trigger this
// function to close all the trades until the leftover assets are rescued.
function closeAllTrades() external {
require(_msgSender() == guardian);
openForTrades = false;
openForFreeTrades = false;
}
function setConverter(address _converter) external onlyOwner {
converter = _converter;
}
function setMarketRegistry(MarketRegistry _marketRegistry) external onlyOwner {
marketRegistry = _marketRegistry;
}
function _transferEth(address _to, uint256 _amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), _to, _amount, 0, 0, 0, 0)
}
require(callStatus, "_transferEth: Eth transfer failed");
}
function _collectFee(uint256[2] memory feeDetails) internal {
require(feeDetails[1] >= baseFees, "Insufficient fee");
if (feeDetails[1] > 0) {
AffiliateDetails memory affiliateDetails = affiliates[feeDetails[0]];
affiliateDetails.isActive
? _transferEth(affiliateDetails.affiliate, feeDetails[1])
: _transferEth(GOV, feeDetails[1]);
}
}
function _checkCallResult(bool _success) internal pure {
if (!_success) {
// Copy revert reason from call
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
function _transferFromHelper(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details
) internal {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
}
// transfer ERC721 tokens from the sender to this contract
for (uint256 i = 0; i < erc721Details.length; i++) {
// accept CryptoPunks
if (erc721Details[i].tokenAddr == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) {
_acceptCryptoPunk(erc721Details[i]);
}
// accept Mooncat
else if (erc721Details[i].tokenAddr == 0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6) {
_acceptMoonCat(erc721Details[i]);
}
// default
else {
for (uint256 j = 0; j < erc721Details[i].ids.length; j++) {
IERC721(erc721Details[i].tokenAddr).transferFrom(
_msgSender(),
address(this),
erc721Details[i].ids[j]
);
}
}
}
// transfer ERC1155 tokens from the sender to this contract
for (uint256 i = 0; i < erc1155Details.length; i++) {
IERC1155(erc1155Details[i].tokenAddr).safeBatchTransferFrom(
_msgSender(),
address(this),
erc1155Details[i].ids,
erc1155Details[i].amounts,
""
);
}
}
function _conversionHelper(
ConverstionDetails[] memory _converstionDetails
) internal {
for (uint256 i = 0; i < _converstionDetails.length; i++) {
// convert to desired asset
(bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
// check if the call passed successfully
_checkCallResult(success);
}
}
function _trade(
MarketRegistry.TradeDetails[] memory _tradeDetails
) internal {
for (uint256 i = 0; i < _tradeDetails.length; i++) {
// get market details
(address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// market should be active
require(_isActive, "_trade: InActive Market");
// execute trade
if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) {
_proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
} else {
(bool success, ) = _isLib
? _proxy.delegatecall(_tradeDetails[i].tradeData)
: _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// check if the call passed successfully
_checkCallResult(success);
}
}
}
// function _tradeSponsored(
// MarketRegistry.TradeDetails[] memory _tradeDetails,
// uint256 sponsoredMarketId
// ) internal returns (bool isSponsored) {
// for (uint256 i = 0; i < _tradeDetails.length; i++) {
// // check if the trade is for the sponsored market
// if (_tradeDetails[i].marketId == sponsoredMarketId) {
// isSponsored = true;
// }
// // get market details
// (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// // market should be active
// require(_isActive, "_trade: InActive Market");
// // execute trade
// if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) {
// _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// } else {
// (bool success, ) = _isLib
// ? _proxy.delegatecall(_tradeDetails[i].tradeData)
// : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// // check if the call passed successfully
// _checkCallResult(success);
// }
// }
// }
function _returnDust(address[] memory _tokens) internal {
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
// return remaining tokens (if any)
for (uint256 i = 0; i < _tokens.length; i++) {
if (IERC20(_tokens[i]).balanceOf(address(this)) > 0) {
_tokens[i].call(abi.encodeWithSelector(0xa9059cbb, msg.sender, IERC20(_tokens[i]).balanceOf(address(this))));
}
}
}
function batchBuyFromOpenSea(
OpenseaTrades[] memory openseaTrades
) payable external nonReentrant {
// execute trades
for (uint256 i = 0; i < openseaTrades.length; i++) {
// execute trade
address(0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b).call{value:openseaTrades[i].value}(openseaTrades[i].tradeData);
}
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithETH(
MarketRegistry.TradeDetails[] memory tradeDetails
) payable external nonReentrant {
// execute trades
_trade(tradeDetails);
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithERC20s(
ERC20Details memory erc20Details,
MarketRegistry.TradeDetails[] memory tradeDetails,
ConverstionDetails[] memory converstionDetails,
address[] memory dustTokens
) payable external nonReentrant {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
}
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// swaps any combination of ERC-20/721/1155
// User needs to approve assets before invoking swap
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
function multiAssetSwap(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memory dustTokens,
uint256[2] memory feeDetails // [affiliateIndex, ETH fee in Wei]
) payable external isOpenForTrades nonReentrant {
// collect fees
_collectFee(feeDetails);
// transfer all tokens
_transferFromHelper(
erc20Details,
erc721Details,
erc1155Details
);
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// Utility function that is used for free swaps for sponsored markets
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
// function multiAssetSwapWithoutFee(
// ERC20Details memory erc20Details,
// SpecialTransferHelper.ERC721Details[] memory erc721Details,
// ERC1155Details[] memory erc1155Details,
// ConverstionDetails[] memory converstionDetails,
// MarketRegistry.TradeDetails[] memory tradeDetails,
// address[] memory dustTokens,
// uint256 sponsoredMarketIndex
// ) payable external isOpenForFreeTrades nonReentrant {
// // fetch the marketId of the sponsored market
// SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];
// // check if the market is active
// require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market");
//
// // transfer all tokens
// _transferFromHelper(
// erc20Details,
// erc721Details,
// erc1155Details
// );
//
// // Convert any assets if needed
// _conversionHelper(converstionDetails);
//
// // execute trades
// bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);
//
// // check if the trades include the sponsored market
// require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market");
//
// // return dust tokens (if any)
// _returnDust(dustTokens);
// }
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0x150b7a02;
}
// Used by ERC721BasicToken.sol
function onERC721Received(
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0xf0b9e5ba;
}
function supportsInterface(bytes4 interfaceId)
external
virtual
view
returns (bool)
{
return interfaceId == this.supportsInterface.selector;
}
receive() external payable {}
// Emergency function: In case any ETH get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueETH(address recipient) onlyOwner external {
_transferEth(recipient, address(this).balance);
}
// Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC20(address asset, address recipient) onlyOwner external {
asset.call(abi.encodeWithSelector(0xa9059cbb, recipient, IERC20(asset).balanceOf(address(this))));
}
// Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC721(asset).transferFrom(address(this), recipient, ids[i]);
}
}
// Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], "");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private reentrancyStatus = 1;
modifier nonReentrant() {
require(reentrancyStatus == 1, "REENTRANCY");
reentrancyStatus = 2;
_;
reentrancyStatus = 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
contract MarketRegistry is Ownable {
struct TradeDetails {
uint256 marketId;
uint256 value;
bytes tradeData;
}
struct Market {
address proxy;
bool isLib;
bool isActive;
}
Market[] public markets;
constructor(address[] memory proxies, bool[] memory isLibs) {
for (uint256 i = 0; i < proxies.length; i++) {
markets.push(Market(proxies[i], isLibs[i], true));
}
}
function addMarket(address proxy, bool isLib) external onlyOwner {
markets.push(Market(proxy, isLib, true));
}
function setMarketStatus(uint256 marketId, bool newStatus) external onlyOwner {
Market storage market = markets[marketId];
market.isActive = newStatus;
}
function setMarketProxy(uint256 marketId, address newProxy, bool isLib) external onlyOwner {
Market storage market = markets[marketId];
market.proxy = newProxy;
market.isLib = isLib;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "../../interfaces/punks/ICryptoPunks.sol";
import "../../interfaces/punks/IWrappedPunk.sol";
import "../../interfaces/mooncats/IMoonCatsRescue.sol";
contract SpecialTransferHelper is Context {
struct ERC721Details {
address tokenAddr;
address[] to;
uint256[] ids;
}
function _uintToBytes5(uint256 id)
internal
pure
returns (bytes5 slicedDataBytes5)
{
bytes memory _bytes = new bytes(32);
assembly {
mstore(add(_bytes, 32), id)
}
bytes memory tempBytes;
assembly {
// 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(5, 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, 5)
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))), 27)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, 5)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
assembly {
slicedDataBytes5 := mload(add(tempBytes, 32))
}
}
function _acceptMoonCat(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
bytes5 catId = _uintToBytes5(erc721Details.ids[i]);
address owner = IMoonCatsRescue(erc721Details.tokenAddr).catOwners(catId);
require(owner == _msgSender(), "_acceptMoonCat: invalid mooncat owner");
IMoonCatsRescue(erc721Details.tokenAddr).acceptAdoptionOffer(catId);
}
}
function _transferMoonCat(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
IMoonCatsRescue(erc721Details.tokenAddr).giveCat(_uintToBytes5(erc721Details.ids[i]), erc721Details.to[i]);
}
}
function _acceptCryptoPunk(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
address owner = ICryptoPunks(erc721Details.tokenAddr).punkIndexToAddress(erc721Details.ids[i]);
require(owner == _msgSender(), "_acceptCryptoPunk: invalid punk owner");
ICryptoPunks(erc721Details.tokenAddr).buyPunk(erc721Details.ids[i]);
}
}
function _transferCryptoPunk(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
ICryptoPunks(erc721Details.tokenAddr).transferPunk(erc721Details.to[i], erc721Details.ids[i]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC20 {
/**
* @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 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 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 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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC721 {
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external;
function setApprovalForAll(address operator, bool approved) external;
function approve(address to, uint256 tokenId) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function balanceOf(address _owner) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC1155 {
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external;
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface ICryptoPunks {
function punkIndexToAddress(uint index) external view returns(address owner);
function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) external;
function buyPunk(uint punkIndex) external payable;
function transferPunk(address to, uint punkIndex) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IWrappedPunk {
/**
* @dev Mints a wrapped punk
*/
function mint(uint256 punkIndex) external;
/**
* @dev Burns a specific wrapped punk
*/
function burn(uint256 punkIndex) external;
/**
* @dev Registers proxy
*/
function registerProxy() external;
/**
* @dev Gets proxy address
*/
function proxyInfo(address user) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IMoonCatsRescue {
function acceptAdoptionOffer(bytes5 catId) payable external;
function makeAdoptionOfferToAddress(bytes5 catId, uint price, address to) external;
function giveCat(bytes5 catId, address to) external;
function catOwners(bytes5 catId) external view returns(address);
function rescueOrder(uint256 rescueIndex) external view returns(bytes5 catId);
} | @audit This function is used to approve specific tokens to specific market contracts with high volume. This is done in very rare cases for the gas optimization purposes. | function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner {
token.approve(operator, amount);
}
| 89,101 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
/**
* @title Storage
* @dev Store & retrieve value in a variable
* BASE UNITS on ETHEREUM BC: wei
* onlyOwner safety check - if we fund the recipient address setting, then we can set ourselves as the only ppl to modify the smart contract (securing our smart contract via admin access)
* Methods/modifiers needed --------------------------------------------------------------------------------
* set recipient address
* check if recipient address is default or has been set
* platform pays gas fee WHEN RECIPIENT SETS ADDRESS
*
* v14 --------------------------------------------------------------------------------------------
* ToDo --------------------------------------------------------------------------------------------
* check for sufficient balance on SC before deactivating an award (before distributing funds)
*/
contract Nominate {
address public owner;
uint8 awardDurationDays;
address relayerAddress;
constructor() {
owner = msg.sender;
awardDurationDays = 1;
relayerAddress = 0x7714E9182799cE2f92B26E70c9CD55cD1b3c1d38;
}
//**struct are like models in dbs, we can make instances of the Award Struct each time a person is nominated
struct Award {
address payable recipientAddress;
uint donationLimit;
uint donationTotal;
address nominatorAddress;
uint expires;
bool active;
}
//**all awards will be our data structure. it is an object with they key as the award id, and the information of the award struct as the pair in key-pair
mapping(uint => Award) public allAwards;
function setRelayerAddress (address _newRelayerAddress) public onlyOwner() {
relayerAddress = _newRelayerAddress;
}
function donateFunds (uint _awardId) public payable aboveMinimum() awardExist(_awardId) {
require(allAwards[_awardId].recipientAddress != allAwards[_awardId].nominatorAddress, 'this award can not accept any donations until recipient address has been set');
// add donation amount to award
allAwards[_awardId].donationTotal += msg.value;
// log donation
emit Emit_Funds_Donated(msg.sender, address(this), msg.value, _awardId);
// check if award donations has reached amount limit
checkLimit(_awardId);
}
//Notes--This function is invoked only if we are creating a new award (nominator makes a nomination)
function startAwardAndDonate(uint _awardId, address payable _recipientAddress, uint _donationLimit) public payable aboveMinimum() {
require(allAwards[_awardId].active == false && allAwards[_awardId].recipientAddress == address(0), 'this award has already been added to the smart contract');
// createAwardStruct
//createAwardStruct(_awardId, _nominatorAddress, _recipientAddress);
createAwardStruct(_awardId, msg.sender, _recipientAddress, _donationLimit);
// log donation
emit Emit_Funds_Donated(msg.sender, address(this), msg.value, _awardId);
// check if award donations has reached amount limit
checkLimit(_awardId);
}
//Notes--This function is invoked to set the award winners address
function setRecipient(uint _awardId, address payable _recipientAddress) public awardExist(_awardId) {
require(msg.sender == relayerAddress, 'msg.sender is not the designated sender for setting recipient');
//check to see if award id in the object if not reject donation….I.e. person tries to claim award after its expired
//modifier to check if there is an award
//set the award
allAwards[_awardId].recipientAddress = _recipientAddress;
//allAwards[_awardId].recipientAddress = msg.sender; // attached recipientAddress to .send()
// allAwards[_awardId].donationTotal += msg.value; // would an excess amount be sent to pay for gas fee?
emit Set_Recipient(_recipientAddress, _awardId);
}
function setRecipients(uint[] memory _awardIdList, address payable _recipientAddress) public {
require(msg.sender == relayerAddress, 'msg.sender is not the designated sender for setting recipient');
for (uint i = 0; i < _awardIdList.length; i++) {
if (allAwards[_awardIdList[i]].active) {
allAwards[_awardIdList[i]].recipientAddress = _recipientAddress;
}
}
}
//claim reward idea?-when time runs out user logs in and presses claim my award-might
// expiration check made on app
// check for expiration on SC before invoking expireAward?
function expireAward(uint _awardId) public awardExist(_awardId) {
// onlyOwner modifier?
deactivateAward(_awardId);
}
// Helpper Functions -----------------------------------------------------------------------------------------------------
function checkLimit(uint _awardId) internal {
if (allAwards[_awardId].donationLimit <= allAwards[_awardId].donationTotal) {
// emit goal reached
emit Award_Goal_Reached(allAwards[_awardId].recipientAddress, address(this), allAwards[_awardId].donationTotal, _awardId);
// end lifecycle of award
deactivateAward(_awardId);
}
}
function deactivateAward(uint _awardId) public awardExist(_awardId) {
//donationTotal back to 0
uint amount = allAwards[_awardId].donationTotal;
allAwards[_awardId].donationTotal = 0;
// execute distribution of donations (amount sent to recipient == amount donated to respective award)
allAwards[_awardId].recipientAddress.transfer(amount);
// emit distribution
emit Award_Distributed(allAwards[_awardId].recipientAddress, address(this), allAwards[_awardId].donationTotal, _awardId);
// set struct property
allAwards[_awardId].active = false;
// emit award deactivated
emit Award_Deactivated(allAwards[_awardId].recipientAddress, address(this), allAwards[_awardId].donationTotal, _awardId);
}
function createAwardStruct(uint _awardId, address _nominatorAddress, address payable _recipientAddress, uint _donationLimit ) internal {
Award memory newAward = Award ({
recipientAddress: _recipientAddress,
donationLimit: _donationLimit,
donationTotal: msg.value,
nominatorAddress: _nominatorAddress,
expires: block.timestamp + awardDurationDays * 1 days,
active: true
});
allAwards[_awardId] = newAward;
}
function balanceOfContract() external view returns(uint) {
return address(this).balance;
}
receive() external payable {}
fallback() external {
revert('not actionable');
}
// Modifiers -----------------------------------------------------------------------------------------------------
//used by expireAward as a safety check to make sure that contract is expired before paying the recipient
modifier timeCheck (uint _awardId) {
require(block.timestamp > allAwards[_awardId].expires, "this contract is not expired and payout will not happen");
_;
}
modifier aboveMinimum () {
require( msg.value > 0 ether, "please donate an amount greater than 0 ether");
_;
}
// does award exist?
modifier awardExist (uint _awardId) {
require(allAwards[_awardId].active, 'award is not active');
_;
}
modifier onlyOwner () {
require( msg.sender == owner, 'only the owner may set the relayer address');
_;
}
// Events Emitters -----------------------------------------------------------------------------------------------------
// the "index" keyword lets the log be filtered by those parameters
event Emit_Funds_Donated (
address indexed _from,
address indexed _contract,
uint _value,
uint _awardId
);
event Award_Goal_Reached (
address indexed _to,
address indexed _contract,
uint _value,
uint _awardId
);
event Award_Deactivated (
address indexed _to,
address indexed _contract,
uint _value,
uint _awardId
);
event Award_Distributed (
address indexed _to,
address indexed _contract,
uint _value,
uint _awardId
);
event Set_Recipient (
address indexed _newRecipient,
uint _awardId
);
}
| claim reward idea?-when time runs out user logs in and presses claim my award-might expiration check made on app check for expiration on SC before invoking expireAward? onlyOwner modifier? | function expireAward(uint _awardId) public awardExist(_awardId) {
deactivateAward(_awardId);
}
| 1,752,655 |
pragma solidity ^0.4.11;
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner public returns (bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() public returns (bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
/**
* @dev Direct ownership pass without change/claim pattern. Can be invoked only by current contract owner
*
* @param _to the next contract owner
*
* @return `true` if success, `false` otherwise
*/
function transferContractOwnership(address _to) onlyContractOwner public returns (bool) {
if (_to == 0x0) {
return false;
}
if (pendingContractOwner != 0x0) {
pendingContractOwner = 0x0;
}
contractOwner = _to;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
}
contract MultiEventsHistoryAdapter {
/**
* @dev It is address of MultiEventsHistory caller assuming we are inside of delegate call.
*/
function _self() constant internal returns (address) {
return msg.sender;
}
}
contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter {
event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference);
event Issue(bytes32 indexed symbol, uint value, address indexed by);
event Revoke(bytes32 indexed symbol, uint value, address indexed by);
event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol);
event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value);
event Recovery(address indexed from, address indexed to, address by);
event Error(uint errorCode);
function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) {
Transfer(_from, _to, _symbol, _value, _reference);
}
function emitIssue(bytes32 _symbol, uint _value, address _by) {
Issue(_symbol, _value, _by);
}
function emitRevoke(bytes32 _symbol, uint _value, address _by) {
Revoke(_symbol, _value, _by);
}
function emitOwnershipChange(address _from, address _to, bytes32 _symbol) {
OwnershipChange(_from, _to, _symbol);
}
function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) {
Approve(_from, _spender, _symbol, _value);
}
function emitRecovery(address _from, address _to, address _by) {
Recovery(_from, _to, _by);
}
function emitError(uint _errorCode) {
Error(_errorCode);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ProxyEventsEmitter {
function emitTransfer(address _from, address _to, uint _value);
function emitApprove(address _from, address _spender, uint _value);
}
contract AssetOwningListener {
function assetOwnerAdded(bytes32 _symbol, address _platform, address _owner);
function assetOwnerRemoved(bytes32 _symbol, address _platform, address _owner);
}
/**
* @title ChronoBank Platform.
*
* The official ChronoBank assets platform powering TIME and LHT tokens, and possibly
* other unknown tokens needed later.
* Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed
* at some point, all the events keep appearing at the same place.
*
* Every asset is meant to be used through a proxy contract. Only one proxy contract have access
* rights for a particular asset.
*
* Features: transfers, allowances, supply adjustments, lost wallet access recovery.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract ChronoBankPlatform is Object, ChronoBankPlatformEmitter {
using SafeMath for uint;
uint constant CHRONOBANK_PLATFORM_SCOPE = 15000;
uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0;
uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1;
uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2;
uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3;
uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4;
uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5;
uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6;
uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7;
uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8;
uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9;
uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10;
uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11;
uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12;
uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13;
uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17;
// Structure of a particular asset.
struct Asset {
uint owner; // Asset's owner id.
uint totalSupply; // Asset's total supply.
string name; // Asset's name, for information purposes.
string description; // Asset's description, for information purposes.
bool isReissuable; // Indicates if asset have dynamic or fixed supply.
uint8 baseUnit; // Proposed number of decimals.
mapping(uint => Wallet) wallets; // Holders wallets.
mapping(uint => bool) partowners; // Part-owners of an asset; have less access rights than owner
}
// Structure of an asset holder wallet for particular asset.
struct Wallet {
uint balance;
mapping(uint => uint) allowance;
}
// Structure of an asset holder.
struct Holder {
address addr; // Current address of the holder.
mapping(address => bool) trust; // Addresses that are trusted with recovery proocedure.
}
// Iterable mapping pattern is used for holders.
uint public holdersCount;
mapping(uint => Holder) public holders;
// This is an access address mapping. Many addresses may have access to a single holder.
mapping(address => uint) holderIndex;
// List of symbols that exist in a platform
bytes32[] public symbols;
// Asset symbol to asset mapping.
mapping(bytes32 => Asset) public assets;
// Asset symbol to asset proxy mapping.
mapping(bytes32 => address) public proxies;
/** Co-owners of a platform. Has less access rights than a root contract owner */
mapping(address => bool) public partowners;
// Should use interface of the emitter, but address of events history.
address public eventsHistory;
address public eventsAdmin;
address owningListener;
/**
* Emits Error event with specified error message.
*
* Should only be used if no state changes happened.
*
* @param _errorCode code of an error
*/
function _error(uint _errorCode) internal returns(uint) {
ChronoBankPlatformEmitter(eventsHistory).emitError(_errorCode);
return _errorCode;
}
/**
* Emits Error if called not by asset owner.
*/
modifier onlyOwner(bytes32 _symbol) {
if (isOwner(msg.sender, _symbol)) {
_;
}
}
/**
* Emits Error if called not by asset owner.
*/
modifier onlyEventsAdmin() {
if (eventsAdmin == msg.sender || contractOwner == msg.sender) {
_;
}
}
/**
* @dev UNAUTHORIZED if called not by one of symbol's partowners or owner
*/
modifier onlyOneOfOwners(bytes32 _symbol) {
if (hasAssetRights(msg.sender, _symbol)) {
_;
}
}
/**
* @dev UNAUTHORIZED if called not by one of partowners or contract's owner
*/
modifier onlyOneOfContractOwners() {
if (contractOwner == msg.sender || partowners[msg.sender]) {
_;
}
}
/**
* Emits Error if called not by asset proxy.
*/
modifier onlyProxy(bytes32 _symbol) {
if (proxies[_symbol] == msg.sender) {
_;
}
}
/**
* Emits Error if _from doesn't trust _to.
*/
modifier checkTrust(address _from, address _to) {
if (isTrusted(_from, _to)) {
_;
}
}
/**
* Adds a co-owner of a contract. Might be more than one co-owner
* @dev Allowed to only contract onwer
*
* @param _partowner a co-owner of a contract
*
* @return result code of an operation
*/
function addPartOwner(address _partowner) onlyContractOwner returns (uint) {
partowners[_partowner] = true;
return OK;
}
/**
* Removes a co-owner of a contract
* @dev Should be performed only by root contract owner
*
* @param _partowner a co-owner of a contract
*
* @return result code of an operation
*/
function removePartOwner(address _partowner) onlyContractOwner returns (uint) {
delete partowners[_partowner];
return OK;
}
/**
* Sets EventsHstory contract address.
*
* Can be set only by events history admon or owner.
*
* @param _eventsHistory MultiEventsHistory contract address.
*
* @return success.
*/
function setupEventsHistory(address _eventsHistory) onlyEventsAdmin returns (uint errorCode) {
eventsHistory = _eventsHistory;
return OK;
}
/**
* Sets EventsHstory contract admin address.
*
* Can be set only by contract owner.
*
* @param _eventsAdmin admin contract address.
*
* @return success.
*/
function setupEventsAdmin(address _eventsAdmin) onlyContractOwner returns (uint errorCode) {
eventsAdmin = _eventsAdmin;
return OK;
}
/**
* @dev TODO
*/
function setupAssetOwningListener(address _listener) onlyEventsAdmin public returns (uint) {
owningListener = _listener;
return OK;
}
/**
* Provides a cheap way to get number of symbols registered in a platform
*
* @return number of symbols
*/
function symbolsCount() public constant returns (uint) {
return symbols.length;
}
/**
* Check asset existance.
*
* @param _symbol asset symbol.
*
* @return asset existance.
*/
function isCreated(bytes32 _symbol) constant returns(bool) {
return assets[_symbol].owner != 0;
}
/**
* Returns asset decimals.
*
* @param _symbol asset symbol.
*
* @return asset decimals.
*/
function baseUnit(bytes32 _symbol) constant returns(uint8) {
return assets[_symbol].baseUnit;
}
/**
* Returns asset name.
*
* @param _symbol asset symbol.
*
* @return asset name.
*/
function name(bytes32 _symbol) constant returns(string) {
return assets[_symbol].name;
}
/**
* Returns asset description.
*
* @param _symbol asset symbol.
*
* @return asset description.
*/
function description(bytes32 _symbol) constant returns(string) {
return assets[_symbol].description;
}
/**
* Returns asset reissuability.
*
* @param _symbol asset symbol.
*
* @return asset reissuability.
*/
function isReissuable(bytes32 _symbol) constant returns(bool) {
return assets[_symbol].isReissuable;
}
/**
* Returns asset owner address.
*
* @param _symbol asset symbol.
*
* @return asset owner address.
*/
function owner(bytes32 _symbol) constant returns(address) {
return holders[assets[_symbol].owner].addr;
}
/**
* Check if specified address has asset owner rights.
*
* @param _owner address to check.
* @param _symbol asset symbol.
*
* @return owner rights availability.
*/
function isOwner(address _owner, bytes32 _symbol) constant returns(bool) {
return isCreated(_symbol) && (assets[_symbol].owner == getHolderId(_owner));
}
/**
* Checks if a specified address has asset owner or co-owner rights.
*
* @param _owner address to check.
* @param _symbol asset symbol.
*
* @return owner rights availability.
*/
function hasAssetRights(address _owner, bytes32 _symbol) constant returns (bool) {
uint holderId = getHolderId(_owner);
return isCreated(_symbol) && (assets[_symbol].owner == holderId || assets[_symbol].partowners[holderId]);
}
/**
* Returns asset total supply.
*
* @param _symbol asset symbol.
*
* @return asset total supply.
*/
function totalSupply(bytes32 _symbol) constant returns(uint) {
return assets[_symbol].totalSupply;
}
/**
* Returns asset balance for a particular holder.
*
* @param _holder holder address.
* @param _symbol asset symbol.
*
* @return holder balance.
*/
function balanceOf(address _holder, bytes32 _symbol) constant returns(uint) {
return _balanceOf(getHolderId(_holder), _symbol);
}
/**
* Returns asset balance for a particular holder id.
*
* @param _holderId holder id.
* @param _symbol asset symbol.
*
* @return holder balance.
*/
function _balanceOf(uint _holderId, bytes32 _symbol) constant returns(uint) {
return assets[_symbol].wallets[_holderId].balance;
}
/**
* Returns current address for a particular holder id.
*
* @param _holderId holder id.
*
* @return holder address.
*/
function _address(uint _holderId) constant returns(address) {
return holders[_holderId].addr;
}
/**
* Adds a co-owner for an asset with provided symbol.
* @dev Should be performed by a contract owner or its co-owners
*
* @param _symbol asset's symbol
* @param _partowner a co-owner of an asset
*
* @return errorCode result code of an operation
*/
function addAssetPartOwner(bytes32 _symbol, address _partowner) onlyOneOfOwners(_symbol) public returns (uint) {
uint holderId = _createHolderId(_partowner);
assets[_symbol].partowners[holderId] = true;
_delegateAssetOwnerAdded(_symbol, _partowner);
ChronoBankPlatformEmitter(eventsHistory).emitOwnershipChange(0x0, _partowner, _symbol);
return OK;
}
/**
* Removes a co-owner for an asset with provided symbol.
* @dev Should be performed by a contract owner or its co-owners
*
* @param _symbol asset's symbol
* @param _partowner a co-owner of an asset
*
* @return errorCode result code of an operation
*/
function removeAssetPartOwner(bytes32 _symbol, address _partowner) onlyOneOfOwners(_symbol) public returns (uint) {
uint holderId = getHolderId(_partowner);
delete assets[_symbol].partowners[holderId];
_delegateAssetOwnerRemoved(_symbol, _partowner);
ChronoBankPlatformEmitter(eventsHistory).emitOwnershipChange(_partowner, 0x0, _symbol);
return OK;
}
/**
* Sets Proxy contract address for a particular asset.
*
* Can be set only once for each asset, and only by contract owner.
*
* @param _proxyAddress Proxy contract address.
* @param _symbol asset symbol.
*
* @return success.
*/
function setProxy(address _proxyAddress, bytes32 _symbol) onlyOneOfContractOwners returns(uint) {
if (proxies[_symbol] != 0x0) {
return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS;
}
proxies[_symbol] = _proxyAddress;
return OK;
}
/**
* Transfers asset balance between holders wallets.
*
* @param _fromId holder id to take from.
* @param _toId holder id to give to.
* @param _value amount to transfer.
* @param _symbol asset symbol.
*/
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal {
assets[_symbol].wallets[_fromId].balance = assets[_symbol].wallets[_fromId].balance.sub(_value);
assets[_symbol].wallets[_toId].balance = assets[_symbol].wallets[_toId].balance.add(_value);
}
/**
* Transfers asset balance between holders wallets.
*
* Performs sanity checks and takes care of allowances adjustment.
*
* @param _fromId holder id to take from.
* @param _toId holder id to give to.
* @param _value amount to transfer.
* @param _symbol asset symbol.
* @param _reference transfer comment to be included in a Transfer event.
* @param _senderId transfer initiator holder id.
*
* @return success.
*/
function _transfer(uint _fromId, uint _toId, uint _value, bytes32 _symbol, string _reference, uint _senderId) internal returns(uint) {
// Should not allow to send to oneself.
if (_fromId == _toId) {
return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Should have positive value.
if (_value == 0) {
return _error(CHRONOBANK_PLATFORM_INVALID_VALUE);
}
// Should have enough balance.
if (_balanceOf(_fromId, _symbol) < _value) {
return _error(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE);
}
// Should have enough allowance.
if (_fromId != _senderId && _allowance(_fromId, _senderId, _symbol) < _value) {
return _error(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE);
}
_transferDirect(_fromId, _toId, _value, _symbol);
// Adjust allowance.
if (_fromId != _senderId) {
assets[_symbol].wallets[_fromId].allowance[_senderId] = assets[_symbol].wallets[_fromId].allowance[_senderId].sub(_value);
}
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ChronoBankPlatformEmitter(eventsHistory).emitTransfer(_address(_fromId), _address(_toId), _symbol, _value, _reference);
_proxyTransferEvent(_fromId, _toId, _value, _symbol);
return OK;
}
/**
* Transfers asset balance between holders wallets.
*
* Can only be called by asset proxy.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _symbol asset symbol.
* @param _reference transfer comment to be included in a Transfer event.
* @param _sender transfer initiator address.
*
* @return success.
*/
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) onlyProxy(_symbol) returns(uint) {
return _transfer(getHolderId(_sender), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender));
}
/**
* Ask asset Proxy contract to emit ERC20 compliant Transfer event.
*
* @param _fromId holder id to take from.
* @param _toId holder id to give to.
* @param _value amount to transfer.
* @param _symbol asset symbol.
*/
function _proxyTransferEvent(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal {
if (proxies[_symbol] != 0x0) {
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ProxyEventsEmitter(proxies[_symbol]).emitTransfer(_address(_fromId), _address(_toId), _value);
}
}
/**
* Returns holder id for the specified address.
*
* @param _holder holder address.
*
* @return holder id.
*/
function getHolderId(address _holder) constant returns(uint) {
return holderIndex[_holder];
}
/**
* Returns holder id for the specified address, creates it if needed.
*
* @param _holder holder address.
*
* @return holder id.
*/
function _createHolderId(address _holder) internal returns(uint) {
uint holderId = holderIndex[_holder];
if (holderId == 0) {
holderId = ++holdersCount;
holders[holderId].addr = _holder;
holderIndex[_holder] = holderId;
}
return holderId;
}
/**
* Issues new asset token on the platform.
*
* Tokens issued with this call go straight to contract owner.
* Each symbol can be issued only once, and only by contract owner.
*
* @param _symbol asset symbol.
* @param _value amount of tokens to issue immediately.
* @param _name name of the asset.
* @param _description description for the asset.
* @param _baseUnit number of decimals.
* @param _isReissuable dynamic or fixed supply.
*
* @return success.
*/
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns(uint) {
return issueAsset(_symbol, _value, _name, _description, _baseUnit, _isReissuable, msg.sender);
}
/**
* Issues new asset token on the platform.
*
* Tokens issued with this call go straight to contract owner.
* Each symbol can be issued only once, and only by contract owner.
*
* @param _symbol asset symbol.
* @param _value amount of tokens to issue immediately.
* @param _name name of the asset.
* @param _description description for the asset.
* @param _baseUnit number of decimals.
* @param _isReissuable dynamic or fixed supply.
* @param _account address where issued balance will be held
*
* @return success.
*/
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) onlyOneOfContractOwners public returns(uint) {
// Should have positive value if supply is going to be fixed.
if (_value == 0 && !_isReissuable) {
return _error(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE);
}
// Should not be issued yet.
if (isCreated(_symbol)) {
return _error(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED);
}
uint holderId = _createHolderId(_account);
uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender);
symbols.push(_symbol);
assets[_symbol] = Asset(creatorId, _value, _name, _description, _isReissuable, _baseUnit);
assets[_symbol].wallets[holderId].balance = _value;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
_delegateAssetOwnerAdded(_symbol, _address(creatorId));
ChronoBankPlatformEmitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId));
return OK;
}
/**
* Issues additional asset tokens if the asset have dynamic supply.
*
* Tokens issued with this call go straight to asset owner.
* Can only be called by asset owner.
*
* @param _symbol asset symbol.
* @param _value amount of additional tokens to issue.
*
* @return success.
*/
function reissueAsset(bytes32 _symbol, uint _value) onlyOneOfOwners(_symbol) public returns(uint) {
// Should have positive value.
if (_value == 0) {
return _error(CHRONOBANK_PLATFORM_INVALID_VALUE);
}
Asset storage asset = assets[_symbol];
// Should have dynamic supply.
if (!asset.isReissuable) {
return _error(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET);
}
// Resulting total supply should not overflow.
if (asset.totalSupply + _value < asset.totalSupply) {
return _error(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW);
}
uint holderId = getHolderId(msg.sender);
asset.wallets[holderId].balance = asset.wallets[holderId].balance.add(_value);
asset.totalSupply = asset.totalSupply.add(_value);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ChronoBankPlatformEmitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId));
_proxyTransferEvent(0, holderId, _value, _symbol);
return OK;
}
/**
* Destroys specified amount of senders asset tokens.
*
* @param _symbol asset symbol.
* @param _value amount of tokens to destroy.
*
* @return success.
*/
function revokeAsset(bytes32 _symbol, uint _value) public returns(uint) {
// Should have positive value.
if (_value == 0) {
return _error(CHRONOBANK_PLATFORM_INVALID_VALUE);
}
Asset storage asset = assets[_symbol];
uint holderId = getHolderId(msg.sender);
// Should have enough tokens.
if (asset.wallets[holderId].balance < _value) {
return _error(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS);
}
asset.wallets[holderId].balance = asset.wallets[holderId].balance.sub(_value);
asset.totalSupply = asset.totalSupply.sub(_value);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ChronoBankPlatformEmitter(eventsHistory).emitRevoke(_symbol, _value, _address(holderId));
_proxyTransferEvent(holderId, 0, _value, _symbol);
return OK;
}
/**
* Passes asset ownership to specified address.
*
* Only ownership is changed, balances are not touched.
* Can only be called by asset owner.
*
* @param _symbol asset symbol.
* @param _newOwner address to become a new owner.
*
* @return success.
*/
function changeOwnership(bytes32 _symbol, address _newOwner) onlyOwner(_symbol) public returns(uint) {
if (_newOwner == 0x0) {
return _error(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER);
}
Asset storage asset = assets[_symbol];
uint newOwnerId = _createHolderId(_newOwner);
// Should pass ownership to another holder.
if (asset.owner == newOwnerId) {
return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
address oldOwner = _address(asset.owner);
asset.owner = newOwnerId;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
_delegateAssetOwnerRemoved(_symbol, oldOwner);
_delegateAssetOwnerAdded(_symbol, _newOwner);
ChronoBankPlatformEmitter(eventsHistory).emitOwnershipChange(oldOwner, _newOwner, _symbol);
return OK;
}
/**
* Check if specified holder trusts an address with recovery procedure.
*
* @param _from truster.
* @param _to trustee.
*
* @return trust existance.
*/
function isTrusted(address _from, address _to) constant returns(bool) {
return holders[getHolderId(_from)].trust[_to];
}
/**
* Trust an address to perform recovery procedure for the caller.
*
* @param _to trustee.
*
* @return success.
*/
function trust(address _to) returns(uint) {
uint fromId = _createHolderId(msg.sender);
// Should trust to another address.
if (fromId == getHolderId(_to)) {
return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Should trust to yet untrusted.
if (isTrusted(msg.sender, _to)) {
return _error(CHRONOBANK_PLATFORM_ALREADY_TRUSTED);
}
holders[fromId].trust[_to] = true;
return OK;
}
/**
* Revoke trust to perform recovery procedure from an address.
*
* @param _to trustee.
*
* @return success.
*/
function distrust(address _to) checkTrust(msg.sender, _to) public returns (uint) {
holders[getHolderId(msg.sender)].trust[_to] = false;
return OK;
}
/**
* Perform recovery procedure.
*
* This function logic is actually more of an addAccess(uint _holderId, address _to).
* It grants another address access to recovery subject wallets.
* Can only be called by trustee of recovery subject.
*
* @param _from holder address to recover from.
* @param _to address to grant access to.
*
* @return success.
*/
function recover(address _from, address _to) checkTrust(_from, msg.sender) public returns (uint errorCode) {
// Should recover to previously unused address.
if (getHolderId(_to) != 0) {
return _error(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS);
}
// We take current holder address because it might not equal _from.
// It is possible to recover from any old holder address, but event should have the current one.
address from = holders[getHolderId(_from)].addr;
holders[getHolderId(_from)].addr = _to;
holderIndex[_to] = getHolderId(_from);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: revert this transaction too;
// Recursive Call: safe, all changes already made.
ChronoBankPlatformEmitter(eventsHistory).emitRecovery(from, _to, msg.sender);
return OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* Note: to revoke allowance, one needs to set allowance to 0.
*
* @param _spenderId holder id to set allowance for.
* @param _value amount to allow.
* @param _symbol asset symbol.
* @param _senderId approve initiator holder id.
*
* @return success.
*/
function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns(uint) {
// Asset should exist.
if (!isCreated(_symbol)) {
return _error(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED);
}
// Should allow to another holder.
if (_senderId == _spenderId) {
return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Double Spend Attack checkpoint
if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) {
return _error(CHRONOBANK_PLATFORM_INVALID_INVOCATION);
}
assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: revert this transaction too;
// Recursive Call: safe, all changes already made.
ChronoBankPlatformEmitter(eventsHistory).emitApprove(_address(_senderId), _address(_spenderId), _symbol, _value);
if (proxies[_symbol] != 0x0) {
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value);
}
return OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* Can only be called by asset proxy.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _symbol asset symbol.
* @param _sender approve initiator address.
*
* @return success.
*/
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) onlyProxy(_symbol) public returns (uint) {
return _approve(_createHolderId(_spender), _value, _symbol, _createHolderId(_sender));
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
* @param _symbol asset symbol.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender, bytes32 _symbol) constant returns(uint) {
return _allowance(getHolderId(_from), getHolderId(_spender), _symbol);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _fromId holder id that allowed spending.
* @param _toId holder id that is allowed to spend.
* @param _symbol asset symbol.
*
* @return holder to spender allowance.
*/
function _allowance(uint _fromId, uint _toId, bytes32 _symbol) constant internal returns(uint) {
return assets[_symbol].wallets[_fromId].allowance[_toId];
}
/**
* Prforms allowance transfer of asset balance between holders wallets.
*
* Can only be called by asset proxy.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _symbol asset symbol.
* @param _reference transfer comment to be included in a Transfer event.
* @param _sender allowance transfer initiator address.
*
* @return success.
*/
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) onlyProxy(_symbol) public returns (uint) {
return _transfer(getHolderId(_from), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender));
}
/**
* @dev TODO
*/
function _delegateAssetOwnerAdded(bytes32 _symbol, address _owner) private {
if (owningListener != 0x0) {
AssetOwningListener(owningListener).assetOwnerAdded(_symbol, this, _owner);
}
}
/**
* @dev TODO
*/
function _delegateAssetOwnerRemoved(bytes32 _symbol, address _owner) private {
if (owningListener != 0x0) {
AssetOwningListener(owningListener).assetOwnerRemoved(_symbol, this, _owner);
}
}
} | Returns holder id for the specified address, creates it if needed. _holder holder address. return holder id./ | function _createHolderId(address _holder) internal returns(uint) {
uint holderId = holderIndex[_holder];
if (holderId == 0) {
holderId = ++holdersCount;
holders[holderId].addr = _holder;
holderIndex[_holder] = holderId;
}
return holderId;
}
| 1,762,499 |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal 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 returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal 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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant 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)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title TKRPToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract TKRPToken is StandardToken {
event Destroy(address indexed _from);
string public name = "TKRPToken";
string public symbol = "TKRP";
uint256 public decimals = 18;
uint256 public initialSupply = 500000;
/**
* @dev Contructor that gives the sender all tokens
*/
function TKRPToken() {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
/**
* @dev Destroys tokens from an address, this process is irrecoverable.
* @param _from The address to destroy the tokens from.
*/
function destroyFrom(address _from) onlyOwner returns (bool) {
uint256 balance = balanceOf(_from);
if (balance == 0) throw;
balances[_from] = 0;
totalSupply = totalSupply.sub(balance);
Destroy(_from);
}
}
/**
* @title PreCrowdsale
* @dev Smart contract which collects ETH and in return transfers the TKRPToken to the contributors
* Log events are emitted for each transaction
*/
contract PreCrowdsale is Ownable {
using SafeMath for uint256;
/* Constants */
uint256 public constant TOKEN_CAP = 500000;
uint256 public constant MINIMUM_CONTRIBUTION = 10 finney;
uint256 public constant TOKENS_PER_ETHER = 10000;
uint256 public constant PRE_CROWDSALE_DURATION = 5 days;
/* Public Variables */
TKRPToken public token;
address public preCrowdsaleOwner;
uint256 public tokensSent;
uint256 public preCrowdsaleStartTime;
uint256 public preCrowdsaleEndTime;
bool public crowdSaleIsRunning = false;
/**
* @dev Fallback function which invokes the processContribution function
* @param _tokenAddress TKRP Token address
* @param _to preCrowdsale owner address
*/
function PreCrowdsale(address _tokenAddress, address _to) {
token = TKRPToken(_tokenAddress);
preCrowdsaleOwner = _to;
}
/**
* @dev Fallback function which invokes the processContribution function
*/
function() payable {
if (!crowdSaleIsRunning) throw;
if (msg.value < MINIMUM_CONTRIBUTION) throw;
uint256 contributionInTokens = msg.value.mul(TOKENS_PER_ETHER).div(1 ether);
if (contributionInTokens.add(tokensSent) > TOKEN_CAP) throw;
/* Send the tokens */
token.transfer(msg.sender, contributionInTokens);
tokensSent = tokensSent.add(contributionInTokens);
}
/**
* @dev Starts the preCrowdsale
*/
function start() onlyOwner {
if (preCrowdsaleStartTime != 0) throw;
crowdSaleIsRunning = true;
preCrowdsaleStartTime = now;
preCrowdsaleEndTime = now + PRE_CROWDSALE_DURATION;
}
/**
* @dev A backup fail-safe drain if required
*/
function drain() onlyOwner {
if (!preCrowdsaleOwner.send(this.balance)) throw;
}
/**
* @dev Finalizes the preCrowdsale and sends funds
*/
function finalize() onlyOwner {
if ((preCrowdsaleStartTime == 0 || now < preCrowdsaleEndTime) && tokensSent != TOKEN_CAP) {
throw;
}
if (!preCrowdsaleOwner.send(this.balance)) throw;
crowdSaleIsRunning = false;
}
} | Finalizes the preCrowdsale and sends funds/ | function finalize() onlyOwner {
if ((preCrowdsaleStartTime == 0 || now < preCrowdsaleEndTime) && tokensSent != TOKEN_CAP) {
throw;
}
if (!preCrowdsaleOwner.send(this.balance)) throw;
crowdSaleIsRunning = false;
}
| 15,333,800 |
./full_match/80001/0xDa21C3277F08773b124165632bf5FFd1651fd710/sources/contracts/proxy/ERC1155DaoProxy.sol | returns the prices of the tokens. requirements: ‼ length of arguments must not mismatch. Signature for tokenPriceBatch(uint256[]) : `0x6f027a18` tokenIds ids of the token. return prices of the tokens./ | function tokenPriceBatch(
uint256[] memory tokenIds
) external view returns (uint200[] memory) {
uint200[] memory batchTokenPrice = new uint200[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; ++i) {
batchTokenPrice[i] = tokenPrice(tokenIds[i]);
}
return batchTokenPrice;
}
| 9,494,885 |
pragma solidity >=0.4.24 <0.6.0;
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
*/
library SafeMath2 {
using SafeMath for *;
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = x.add(1).div(2);
y = x;
while (z < y)
{
y = z;
z = x.div(z).add(z).div(2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(x);
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return 0;
else if (y==0)
return 1;
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = z.mul(x);
return z;
}
}
} | gives square. multiplies x by x/ | function sq(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(x);
}
| 965,984 |
./full_match/80001/0xAC703429391Ad2CA417c3E17DD8b169F406C1c30/sources/contracts/Main.sol | just check already registerd or not | function signIn(string memory _address) public view returns (bool) {
if (userNameToData[_address].isexist) return true;
return false;
}
| 9,456,744 |
./full_match/137/0x3dcd833e696DeD5482E704BF169A0de88Eb47D51/sources/quickGame.sol | Heal another player. | function heal(address friend) public lock rested {
require(block.timestamp < gameEnds, "GAME_OVER");
require(isAlive(msg.sender), "YOU_ARE_DEAD");
require(isAlive(friend), "THEY_ARE_DEAD");
require(balanceOf[friend] < 9 ether, "ALREADY_HEALED");
_mint(friend, 1 ether);
lastActionTimestamp[msg.sender] = block.timestamp;
emit Heal(msg.sender, friend);
}
| 3,761,794 |
pragma solidity ^0.4.23;
/**
* @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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Administratable is Ownable {
mapping (address => bool) admins;
event AdminAdded(address indexed _admin);
event AdminRemoved(address indexed _admin);
modifier onlyAdmin() {
require(admins[msg.sender]);
_;
}
function addAdmin(address _addressToAdd) external onlyOwner {
require(_addressToAdd != address(0));
admins[_addressToAdd] = true;
emit AdminAdded(_addressToAdd);
}
function removeAdmin(address _addressToRemove) external onlyOwner {
require(_addressToRemove != address(0));
admins[_addressToRemove] = false;
emit AdminRemoved(_addressToRemove);
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ERC865 is ERC20 {
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool);
function approvePreSigned(
bytes _signature,
address _spender,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool);
function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool);
function decreaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _subtractedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool);
function transferFromPreSigned(
bytes _signature,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool);
function revokeSignature(bytes _signature)
public
returns (bool);
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) public balances;
uint256 _totalSupply;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
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 returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ERC865Token is ERC865, StandardToken {
/* Nonces of transfers performed */
mapping(bytes => bool) nonces;
event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee);
event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee);
event SignatureRevoked(bytes signature, address indexed from);
/**
* @notice Submit a presigned transfer
* @param _signature bytes The signature, issued by the owner.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
{
require(_to != address(0));
require(!nonces[_signature]);
bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
nonces[_signature] = true;
balances[from] = balances[from].sub(_value).sub(_fee);
balances[_to] = balances[_to].add(_value);
balances[msg.sender] = balances[msg.sender].add(_fee);
emit Transfer(from, _to, _value);
emit Transfer(from, msg.sender, _fee);
emit TransferPreSigned(from, _to, msg.sender, _value, _fee);
return true;
}
/**
* @notice Submit a presigned approval
* @param _signature bytes The signature, issued by the owner.
* @param _spender address The address which will spend the funds.
* @param _value uint256 The amount of tokens to allow.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function approvePreSigned(
bytes _signature,
address _spender,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
{
require(_spender != address(0));
require(!nonces[_signature]);
bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _value, _fee, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
nonces[_signature] = true;
allowed[from][_spender] = _value;
balances[from] = balances[from].sub(_fee);
balances[msg.sender] = balances[msg.sender].add(_fee);
emit Approval(from, _spender, _value);
emit Transfer(from, msg.sender, _fee);
emit ApprovalPreSigned(from, _spender, msg.sender, _value, _fee);
return true;
}
/**
* @notice Increase the amount of tokens that an owner allowed to a spender.
* @param _signature bytes The signature, issued by the owner.
* @param _spender address The address which will spend the funds.
* @param _addedValue uint256 The amount of tokens to increase the allowance by.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
{
require(_spender != address(0));
require(!nonces[_signature]);
bytes32 hashedTx = increaseApprovalPreSignedHashing(address(this), _spender, _addedValue, _fee, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
nonces[_signature] = true;
allowed[from][_spender] = allowed[from][_spender].add(_addedValue);
balances[from] = balances[from].sub(_fee);
balances[msg.sender] = balances[msg.sender].add(_fee);
emit Approval(from, _spender, allowed[from][_spender]);
emit Transfer(from, msg.sender, _fee);
emit ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee);
return true;
}
/**
* @notice Decrease the amount of tokens that an owner allowed to a spender.
* @param _signature bytes The signature, issued by the owner
* @param _spender address The address which will spend the funds.
* @param _subtractedValue uint256 The amount of tokens to decrease the allowance by.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function decreaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _subtractedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
{
require(_spender != address(0));
require(!nonces[_signature]);
bytes32 hashedTx = decreaseApprovalPreSignedHashing(address(this), _spender, _subtractedValue, _fee, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
nonces[_signature] = true;
uint oldValue = allowed[from][_spender];
if (_subtractedValue > oldValue) {
allowed[from][_spender] = 0;
} else {
allowed[from][_spender] = oldValue.sub(_subtractedValue);
}
balances[from] = balances[from].sub(_fee);
balances[msg.sender] = balances[msg.sender].add(_fee);
emit Approval(from, _spender, _subtractedValue);
emit Transfer(from, msg.sender, _fee);
emit ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee);
return true;
}
/**
* @notice Transfer tokens from one address to another
* @param _signature bytes The signature, issued by the spender.
* @param _from address The address which you want to send tokens from.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the spender.
* @param _nonce uint256 Presigned transaction number.
*/
function transferFromPreSigned(
bytes _signature,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
{
require(_to != address(0));
require(!nonces[_signature]);
bytes32 hashedTx = transferFromPreSignedHashing(address(this), _from, _to, _value, _fee, _nonce);
address spender = recover(hashedTx, _signature);
require(spender != address(0));
nonces[_signature] = true;
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][spender] = allowed[_from][spender].sub(_value);
balances[spender] = balances[spender].sub(_fee);
balances[msg.sender] = balances[msg.sender].add(_fee);
nonces[_signature] = true;
emit Transfer(_from, _to, _value);
emit Transfer(spender, msg.sender, _fee);
return true;
}
/**
* Revote previously approved signature
* @param _signature bytes The signature to revoke
* @return bool Returns true if revocation was successful
*/
function revokeSignature(bytes _signature) public returns (bool) {
require(!nonces[_signature]);
nonces[_signature] = true;
emit SignatureRevoked(_signature, msg.sender);
return true;
}
/**
* @notice Hash (keccak256) of the payload used by transferPreSigned
* @param _token address The address of the token.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function transferPreSignedHashing(
address _token,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
/* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce);
}
/**
* @notice Hash (keccak256) of the payload used by approvePreSigned
* @param _token address The address of the token
* @param _spender address The address which will spend the funds.
* @param _value uint256 The amount of tokens to allow.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function approvePreSignedHashing(
address _token,
address _spender,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
/* "f7ac9c2e": approvePreSignedHashing(address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0xf7ac9c2e), _token, _spender, _value, _fee, _nonce);
}
/**
* @notice Hash (keccak256) of the payload used by increaseApprovalPreSigned
* @param _token address The address of the token
* @param _spender address The address which will spend the funds.
* @param _addedValue uint256 The amount of tokens to increase the allowance by.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function increaseApprovalPreSignedHashing(
address _token,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
/* "a45f71ff": increaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0xa45f71ff), _token, _spender, _addedValue, _fee, _nonce);
}
/**
* @notice Hash (keccak256) of the payload used by decreaseApprovalPreSigned
* @param _token address The address of the token
* @param _spender address The address which will spend the funds.
* @param _subtractedValue uint256 The amount of tokens to decrease the allowance by.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function decreaseApprovalPreSignedHashing(
address _token,
address _spender,
uint256 _subtractedValue,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
/* "59388d78": decreaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0x59388d78), _token, _spender, _subtractedValue, _fee, _nonce);
}
/**
* @notice Hash (keccak256) of the payload used by transferFromPreSigned
* @param _token address The address of the token
* @param _from address The address which you want to send tokens from.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the spender.
* @param _nonce uint256 Presigned transaction number.
*/
function transferFromPreSignedHashing(
address _token,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
/* "b7656dc5": transferFromPreSignedHashing(address,address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0xb7656dc5), _token, _from, _to, _value, _fee, _nonce);
}
/**
* @notice Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
contract Pausable is Ownable {
event Paused();
event Unpaused();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @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 Paused();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpaused();
}
}
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;
// Amount of token sold in wei
uint256 public tokenWeiSold;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
tokenWeiSold = tokenWeiSold.add(tokens);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) pure 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 Nu mber 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) pure 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);
}
}
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
constructor(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract WhitelistedCrowdsale is Crowdsale, Administratable {
mapping(address => bool) public whitelist;
/**
* Event for logging adding to whitelist
* @param _address the address to add to the whitelist
*/
event AddedToWhitelist(address indexed _address);
/**
* Event for logging removing from whitelist
* @param _address the address to remove from the whitelist
*/
event RemovedFromWhitelist(address indexed _address);
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyAdmin {
whitelist[_beneficiary] = true;
emit AddedToWhitelist(_beneficiary);
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyAdmin {
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 onlyAdmin {
whitelist[_beneficiary] = false;
emit RemovedFromWhitelist(_beneficiary);
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract PostDeliveryCrowdsale is TimedCrowdsale, Administratable {
using SafeMath for uint256;
mapping(address => uint256) public balances;
/**
* Event for logging when token sale tokens are withdrawn
* @param _address the address to withdraw tokens for
* @param _amount the amount withdrawn for this address
*/
event TokensWithdrawn(address indexed _address, uint256 _amount);
/**
* @dev Withdraw tokens only after crowdsale ends.
*/
function withdrawTokens(address _beneficiary) public onlyAdmin {
require(hasClosed());
uint256 amount = balances[_beneficiary];
require(amount > 0);
balances[_beneficiary] = 0;
_deliverTokens(_beneficiary, amount);
emit TokensWithdrawn(_beneficiary, amount);
}
/**
* @dev Overrides parent by storing balances instead of issuing tokens right away.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
function getBalance(address _beneficiary) public returns (uint256) {
return balances[_beneficiary];
}
}
contract MultiRoundCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
struct SaleRound {
uint256 start;
uint256 end;
uint256 rate;
uint256 roundCap;
uint256 minPurchase;
}
SaleRound seedRound;
SaleRound presale;
SaleRound crowdsaleWeek1;
SaleRound crowdsaleWeek2;
SaleRound crowdsaleWeek3;
SaleRound crowdsaleWeek4;
bool public saleRoundsSet = false;
/**
* Sets the parameters for each round.
*
* Each round is defined by an array, with each field mapping to a field in the SaleRound struct.
* The array elements are as follows:
* array[0]: start time of the round
* array[1]: end time of the round
* array[2]: the exchange rate of this round. i.e number of TIP per ETH
* array[3]: The cumulative cap of this round
* array[4]: Minimum purchase of this round
*
* @param _seedRound [description]
* @param _presale [description]
* @param _crowdsaleWeek1 [description]
* @param _crowdsaleWeek2 [description]
* @param _crowdsaleWeek3 [description]
* @param _crowdsaleWeek4 [description]
*/
function setTokenSaleRounds(uint256[5] _seedRound, uint256[5] _presale, uint256[5] _crowdsaleWeek1, uint256[5] _crowdsaleWeek2, uint256[5] _crowdsaleWeek3, uint256[5] _crowdsaleWeek4) external onlyOwner returns (bool) {
// This function can only be called once
require(!saleRoundsSet);
// Check that each round end time is after the start time
require(_seedRound[0] < _seedRound[1]);
require(_presale[0] < _presale[1]);
require(_crowdsaleWeek1[0] < _crowdsaleWeek1[1]);
require(_crowdsaleWeek2[0] < _crowdsaleWeek2[1]);
require(_crowdsaleWeek3[0] < _crowdsaleWeek3[1]);
require(_crowdsaleWeek4[0] < _crowdsaleWeek4[1]);
// Check that each round ends before the next begins
require(_seedRound[1] < _presale[0]);
require(_presale[1] < _crowdsaleWeek1[0]);
require(_crowdsaleWeek1[1] < _crowdsaleWeek2[0]);
require(_crowdsaleWeek2[1] < _crowdsaleWeek3[0]);
require(_crowdsaleWeek3[1] < _crowdsaleWeek4[0]);
seedRound = SaleRound(_seedRound[0], _seedRound[1], _seedRound[2], _seedRound[3], _seedRound[4]);
presale = SaleRound(_presale[0], _presale[1], _presale[2], _presale[3], _presale[4]);
crowdsaleWeek1 = SaleRound(_crowdsaleWeek1[0], _crowdsaleWeek1[1], _crowdsaleWeek1[2], _crowdsaleWeek1[3], _crowdsaleWeek1[4]);
crowdsaleWeek2 = SaleRound(_crowdsaleWeek2[0], _crowdsaleWeek2[1], _crowdsaleWeek2[2], _crowdsaleWeek2[3], _crowdsaleWeek2[4]);
crowdsaleWeek3 = SaleRound(_crowdsaleWeek3[0], _crowdsaleWeek3[1], _crowdsaleWeek3[2], _crowdsaleWeek3[3], _crowdsaleWeek3[4]);
crowdsaleWeek4 = SaleRound(_crowdsaleWeek4[0], _crowdsaleWeek4[1], _crowdsaleWeek4[2], _crowdsaleWeek4[3], _crowdsaleWeek4[4]);
saleRoundsSet = true;
return saleRoundsSet;
}
function getCurrentRound() internal view returns (SaleRound) {
require(saleRoundsSet);
uint256 currentTime = block.timestamp;
if (currentTime > seedRound.start && currentTime <= seedRound.end) {
return seedRound;
} else if (currentTime > presale.start && currentTime <= presale.end) {
return presale;
} else if (currentTime > crowdsaleWeek1.start && currentTime <= crowdsaleWeek1.end) {
return crowdsaleWeek1;
} else if (currentTime > crowdsaleWeek2.start && currentTime <= crowdsaleWeek2.end) {
return crowdsaleWeek2;
} else if (currentTime > crowdsaleWeek3.start && currentTime <= crowdsaleWeek3.end) {
return crowdsaleWeek3;
} else if (currentTime > crowdsaleWeek4.start && currentTime <= crowdsaleWeek4.end) {
return crowdsaleWeek4;
} else {
revert();
}
}
function getCurrentRate() public view returns (uint256) {
require(saleRoundsSet);
SaleRound memory currentRound = getCurrentRound();
return currentRound.rate;
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
require(_weiAmount != 0);
uint256 currentRate = getCurrentRate();
require(currentRate != 0);
return currentRate.mul(_weiAmount);
}
}
contract TipToken is ERC865Token, Ownable {
using SafeMath for uint256;
uint256 public constant TOTAL_SUPPLY = 10 ** 9;
string public constant name = "Tip Token";
string public constant symbol = "TIP";
uint8 public constant decimals = 18;
mapping (address => string) aliases;
mapping (string => address) addresses;
/**
* Constructor
*/
constructor() public {
_totalSupply = TOTAL_SUPPLY * (10**uint256(decimals));
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
/**
* Returns the available supple (total supply minus tokens held by owner)
*/
function availableSupply() public view returns (uint256) {
return _totalSupply.sub(balances[owner]).sub(balances[address(0)]);
}
/**
* Token owner can approve for `spender` to transferFrom(...) `tokens`
* from the token owner's account. The `spender` contract function
* `receiveApproval(...)` is then executed
*/
function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
/**
* Don't accept ETH.
*/
function () public payable {
revert();
}
/**
* Owner can transfer out any accidentally sent ERC20 tokens
*/
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
/**
* Sets the alias for the msg.sender's address.
* @param alias the alias to attach to an address
*/
function setAlias(string alias) public {
aliases[msg.sender] = alias;
addresses[alias] = msg.sender;
}
}
contract TipTokenCrowdsale is MultiRoundCrowdsale, CappedCrowdsale, WhitelistedCrowdsale, AllowanceCrowdsale, PostDeliveryCrowdsale, Pausable {
/**
* Contract name
* String name - the name of the contract
*/
string public constant name = "Tip Token Crowdsale";
/**
* @param _vault Address where collected funds will be forwarded to
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
* @param _cap the maximum number of tokens to be collected in the sale
* @param _token Address of the token being sold
*/
constructor(
ERC20 _token,
address _tokenWallet,
address _vault,
uint256 _cap,
uint256 _start, uint256 _end, uint256 _baseRate
) public
Crowdsale(_baseRate, _vault, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_start, _end)
PostDeliveryCrowdsale()
WhitelistedCrowdsale()
AllowanceCrowdsale(_tokenWallet)
MultiRoundCrowdsale()
{
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused() {
super._preValidatePurchase(_beneficiary, _weiAmount);
SaleRound memory currentRound = getCurrentRound();
require(weiRaised.add(_weiAmount) <= currentRound.roundCap);
require(balances[_beneficiary].add(_weiAmount) >= currentRound.minPurchase);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return MultiRoundCrowdsale._getTokenAmount(_weiAmount);
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
AllowanceCrowdsale._deliverTokens(_beneficiary, _tokenAmount);
}
} | Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. _beneficiaries Addresses to be added to the whitelist/ | function addManyToWhitelist(address[] _beneficiaries) external onlyAdmin {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
| 92,487 |
/**
*Submitted for verification at Etherscan.io on 2022-02-01
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File: AddressUpgradeable.sol
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity\'s `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: BadgerGuestlistApi.sol
interface BadgerGuestListAPI {
function authorized(
address guest,
uint256 amount,
bytes32[] calldata merkleProof
) external view returns (bool);
function setGuests(address[] calldata _guests, bool[] calldata _invited)
external;
}
// File: IController.sol
interface IController {
function withdraw(address, uint256) external;
function strategies(address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
// File: IERC20Detailed.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Detailed {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
/**
* @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: IERC20Upgradeable.sol
/**
* @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
);
}
// File: IGac.sol
interface IGac {
function DEV_MULTISIG() external view returns (address);
function WAR_ROOM_ACL() external view returns (address);
function BLACKLISTED_ROLE() external view returns (bytes32);
function paused() external view returns (bool);
function transferFromDisabled() external view returns (bool);
function isBlacklisted(address account) external view returns (bool);
function unpause() external;
function pause() external;
function enableTransferFrom() external;
function disableTransferFrom() external;
}
// File: Initializable.sol
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can\'t have a constructor, it\'s common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
}
// File: SafeMathUpgradeable.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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity\'s `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity\'s `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity\'s `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity\'s `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring \'a\' not being zero, but the
// benefit is lost if \'b\' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity\'s `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity\'s `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn\'t hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity\'s `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity\'s `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: ContextUpgradeable.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: SafeERC20Upgradeable.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 SafeMathUpgradeable for uint256;
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).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20Upgradeable 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(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"
);
}
}
}
// File: SettAccessControl.sol
/*
Common base for permissioned roles throughout Sett ecosystem
*/
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(
msg.sender == strategist || msg.sender == governance,
"onlyGovernanceOrStrategist"
);
}
function _onlyAuthorizedActors() internal view {
require(
msg.sender == keeper || msg.sender == governance,
"onlyAuthorizedActors"
);
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
// File: ERC20Upgradeable.sol
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn\'t required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is
Initializable,
ContextUpgradeable,
IERC20Upgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol)
internal
initializer
{
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol)
internal
initializer
{
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``\'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``\'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``\'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[44] private __gap;
}
// File: OwnableUpgradeable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: PausableUpgradeable.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.
*/
contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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() virtual {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: SettAccessControlDefended.sol
/*
Add ability to prevent unwanted contract access to Sett permissions
*/
contract SettAccessControlDefended is SettAccessControl {
mapping(address => bool) public approved;
function approveContractAccess(address account) external {
_onlyGovernance();
approved[account] = true;
}
function revokeContractAccess(address account) external {
_onlyGovernance();
approved[account] = false;
}
function _defend() internal view returns (bool) {
require(
approved[msg.sender] || msg.sender == tx.origin,
"Access denied for caller"
);
}
uint256[50] private __gap;
}
// File: RemDIGG.sol
/*
Source: https://github.com/iearn-finance/yearn-protocol/blob/develop/contracts/vaults/yVault.sol
Changelog:
V1.1
* Strategist no longer has special function calling permissions
* Version function added to contract
* All write functions, with the exception of transfer, are pausable
* Keeper or governance can pause
* Only governance can unpause
V1.2
* Transfer functions are now pausable along with all other non-permissioned write functions
* All permissioned write functions, with the exception of pause() & unpause(), are pausable as well
V1.3
* Add guest list functionality
* All deposits can be optionally gated by external guestList approval logic on set guestList contract
V1.4
* Add depositFor() to deposit on the half of other users. That user will then be blockLocked.
V1.Rem
* RemBadger Version
* Allows for one time dilution of ppfs by minting extra shares (briked after)
* DepositBricked to track when deposits can no longer be done (irreversible)
V1.RemDIGG
* Same deal, just different token
*/
contract RemDIGG is ERC20Upgradeable, SettAccessControlDefended, PausableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
IGac public constant GAC = IGac(0x9c58B0D88578cd75154Bdb7C8B013f7157bae35a); // Set in initializer because of tests is unchangeable (because contract is upgradeable)
IERC20Upgradeable public token;
uint256 public min;
uint256 public constant max = 10000;
address public controller;
mapping(address => uint256) public blockLock;
address public guardian;
// Packed in same slot (and I believe the slot goes hot in deposits so ideal)
BadgerGuestListAPI public guestList;
bool public depositsEnded;
event FullPricePerShareUpdated(uint256 value, uint256 indexed timestamp, uint256 indexed blockNumber);
event DepositBricked(uint256 indexed timestamp);
modifier whenNotPaused() override {
require(!paused(), "Pausable: paused");
require(!GAC.paused(), "Pausable: GAC Paused");
_;
}
function initialize(
address _token,
address _controller,
address _governance,
address _keeper,
address _guardian,
bool _overrideTokenName,
string memory _namePrefix, // NOTE: Unused but because template we keep them
string memory _symbolPrefix // NOTE: Unused but because template we keep them
) public initializer whenNotPaused {
IERC20Detailed namedToken = IERC20Detailed(_token);
__ERC20_init("remDIGG", "remDIGG");
token = IERC20Upgradeable(_token);
governance = _governance;
strategist = address(0);
keeper = _keeper;
controller = _controller;
guardian = _guardian;
min = 9500;
emit FullPricePerShareUpdated(getPricePerFullShare(), now, block.number);
// Paused on launch
_pause();
}
/// @dev Sets `depositsEnded` to true blocking deposits forever
/// @notice automatically called when calling `mintExtra`
function brickDeposits() public {
_onlyGovernance();
depositsEnded = true;
emit DepositBricked(block.timestamp);
}
/// @dev Mint more shares, diluting the ppfs
/// @notice This bricks deposit to avoid griefing, can only call once!!
function mintExtra(uint256 amount) external {
require(!depositsEnded, "You can mint extra only until you brick deposits");
_onlyGovernance();
// Mint Tokens, diluting the ppfs of tokens below 1
_mint(msg.sender, amount);
// Brick deposits from now on
brickDeposits();
}
/// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedPausers() internal view {
require(msg.sender == guardian || msg.sender == governance, "onlyPausers");
}
function _blockLocked() internal view {
require(blockLock[msg.sender] < block.number, "blockLocked");
}
function _blacklisted(address _recipient) internal view {
require(!GAC.isBlacklisted(_recipient), "blacklisted");
}
/// ===== View Functions =====
function version() public view returns (string memory) {
return "1.4r - remDIGG";
}
function getPricePerFullShare() public virtual view returns (uint256) {
if (totalSupply() == 0) {
return 1e18;
}
return balance().mul(1e18).div(totalSupply());
}
/// @notice Return the total balance of the underlying token within the system
/// @notice Sums the balance in the Sett, the Controller, and the Strategy
function balance() public virtual view returns (uint256) {
return token.balanceOf(address(this)).add(IController(controller).balanceOf(address(token)));
}
/// @notice Defines how much of the Setts\' underlying can be borrowed by the Strategy for use
/// @notice Custom logic in here for how much the vault allows to be borrowed
/// @notice Sets minimum required on-hand to keep small withdrawals cheap
function available() public virtual view returns (uint256) {
return token.balanceOf(address(this)).mul(min).div(max);
}
/// ===== Public Actions =====
/// @notice Deposit assets into the Sett, and return corresponding shares to the user
/// @notice Only callable by EOA accounts that pass the _defend() check
function deposit(uint256 _amount) public whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_depositWithAuthorization(_amount, new bytes32[](0));
}
/// @notice Deposit variant with proof for merkle guest list
function deposit(uint256 _amount, bytes32[] memory proof) public whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_depositWithAuthorization(_amount, proof);
}
/// @notice Convenience function: Deposit entire balance of asset into the Sett, and return corresponding shares to the user
/// @notice Only callable by EOA accounts that pass the _defend() check
function depositAll() external whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_depositWithAuthorization(token.balanceOf(msg.sender), new bytes32[](0));
}
/// @notice DepositAll variant with proof for merkle guest list
function depositAll(bytes32[] memory proof) external whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_depositWithAuthorization(token.balanceOf(msg.sender), proof);
}
/// @notice Deposit assets into the Sett, and return corresponding shares to the user
/// @notice Only callable by EOA accounts that pass the _defend() check
function depositFor(address _recipient, uint256 _amount) public whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(_recipient);
_depositForWithAuthorization(_recipient, _amount, new bytes32[](0));
}
/// @notice Deposit variant with proof for merkle guest list
function depositFor(
address _recipient,
uint256 _amount,
bytes32[] memory proof
) public whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(_recipient);
_depositForWithAuthorization(_recipient, _amount, proof);
}
/// @notice No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares) public whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_withdraw(_shares);
}
/// @notice Convenience function: Withdraw all shares of the sender
function withdrawAll() external whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_withdraw(balanceOf(msg.sender));
}
/// ===== Permissioned Actions: Governance =====
function setGuestList(address _guestList) external whenNotPaused {
_onlyGovernance();
guestList = BadgerGuestListAPI(_guestList);
}
/// @notice Set minimum threshold of underlying that must be deposited in strategy
/// @notice Can only be changed by governance
function setMin(uint256 _min) external whenNotPaused {
_onlyGovernance();
min = _min;
}
/// @notice Change controller address
/// @notice Can only be changed by governance
function setController(address _controller) public whenNotPaused {
_onlyGovernance();
controller = _controller;
}
/// @notice Change guardian address
/// @notice Can only be changed by governance
function setGuardian(address _guardian) external whenNotPaused {
_onlyGovernance();
guardian = _guardian;
}
/// ===== Permissioned Actions: Controller =====
/// @notice Used to swap any borrowed reserve over the debt limit to liquidate to \'token\'
/// @notice Only controller can trigger harvests
function harvest(address reserve, uint256 amount) external whenNotPaused {
_onlyController();
require(reserve != address(token), "token");
IERC20Upgradeable(reserve).safeTransfer(controller, amount);
}
/// ===== Permissioned Functions: Trusted Actors =====
/// @notice Transfer the underlying available to be claimed to the controller
/// @notice The controller will deposit into the Strategy for yield-generating activities
/// @notice Permissionless operation
function earn() public whenNotPaused {
_onlyAuthorizedActors();
uint256 _bal = available();
token.safeTransfer(controller, _bal);
IController(controller).earn(address(token), _bal);
}
/// @dev Emit event tracking current full price per share
/// @dev Provides a pure on-chain way of approximating APY
function trackFullPricePerShare() external whenNotPaused {
_onlyAuthorizedActors();
emit FullPricePerShareUpdated(getPricePerFullShare(), now, block.number);
}
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Implementations =====
/// @dev Calculate the number of shares to issue for a given deposit
/// @dev This is based on the realized value of underlying assets between Sett & associated Strategy
// @dev deposit for msg.sender
function _deposit(uint256 _amount) internal {
_depositFor(msg.sender, _amount);
}
function _depositFor(address recipient, uint256 _amount) internal virtual {
require(!depositsEnded, "No longer accepting Deposits");
_onlyGovernance();
uint256 _pool = balance();
uint256 _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(recipient, shares);
}
function _depositWithAuthorization(uint256 _amount, bytes32[] memory proof) internal virtual {
if (address(guestList) != address(0)) {
require(guestList.authorized(msg.sender, _amount, proof), "guest-list-authorization");
}
_deposit(_amount);
}
function _depositForWithAuthorization(
address _recipient,
uint256 _amount,
bytes32[] memory proof
) internal virtual {
if (address(guestList) != address(0)) {
require(guestList.authorized(_recipient, _amount, proof), "guest-list-authorization");
}
_depositFor(_recipient, _amount);
}
// No rebalance implementation for lower fees and faster swaps
function _withdraw(uint256 _shares) internal virtual {
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint256 b = token.balanceOf(address(this));
if (b < r) {
uint256 _toWithdraw = r.sub(b);
IController(controller).withdraw(address(token), _toWithdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _toWithdraw) {
r = b.add(_diff);
}
}
token.safeTransfer(msg.sender, r);
}
function _lockForBlock(address account) internal {
blockLock[account] = block.number;
}
/// ===== ERC20 Overrides =====
/// @dev Add blockLock to transfers, users cannot transfer tokens in the same block as a deposit or withdrawal.
function transfer(address recipient, uint256 amount) public virtual override whenNotPaused returns (bool) {
_blockLocked();
_blacklisted(msg.sender);
return super.transfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override whenNotPaused returns (bool) {
_blockLocked();
_blacklisted(msg.sender);
_blacklisted(sender);
require(!GAC.transferFromDisabled(), "transferFrom: GAC transferFromDisabled");
return super.transferFrom(sender, recipient, amount);
}
} | Interface of the ERC20 standard as defined in the EIP./ | interface IERC20Detailed {
function totalSupply() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
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
);
}
| 6,657,110 |
./full_match/1/0x8CD834258d000166769733Dfb5fB6fD6E43dB4e7/sources/@nftculture/nftc-contracts/contracts/token/solbase/ERC721/ERC721.sol | Ownership check above ensures no underflow. | function _burn(uint256 id) internal virtual {
address owner = _ownerOf[id];
if (owner == address(0)) revert NotMinted();
unchecked {
_balanceOf[owner]--;
}
delete _ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
| 4,861,758 |
./full_match/1/0xd92D8183E6ECb3401C47f41b42aFe6EE0EFe6257/sources/BabyBumbleBee.sol | 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, "BumbleBeeMath: subtraction overflow");
}
| 3,860,134 |
./full_match/43113/0x5eDb1fD030f0C98C05dBccc7d0D01cD99DDA34f1/sources/interfaces/IERC165.sol | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
pragma solidity 0.8.0;
} | 7,189,573 |
/**
*Submitted for verification at Etherscan.io on 2022-02-19
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
// File: soulswap-core/contracts/interfaces/IERC20.sol
interface IERC20 {
// events
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed owner, address indexed spender, uint value);
// token details
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
// address details
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function getOwner() external view returns (address);
// token actions
function approve(address spender, uint value) external returns (bool);
function transfer(address recipient, uint value) external returns (bool);
function transferFrom(address sender, address recipient, uint value) external returns (bool);
}
// File: contracts/interfaces/ISoulSwapRouter01.sol
pragma solidity >=0.6.2;
interface ISoulSwapRouter01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external payable returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external payable returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts/interfaces/ISoulSwapRouter02.sol
pragma solidity >=0.6.2;
interface ISoulSwapRouter02 is ISoulSwapRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts/interfaces/ISoulSwapFactory.sol
pragma solidity >=0.5.0;
interface ISoulSwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event SetFeeTo(address indexed user, address indexed _feeTo);
event SetMigrator(address indexed user, address indexed _migrator);
event FeeToSetter(address indexed user, address indexed _feeToSetter);
function feeTo() external view returns (address _feeTo);
function feeToSetter() external view returns (address _feeToSetter);
function migrator() external view returns (address _migrator);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setMigrator(address) external;
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: soulswap-lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File: soulswap-core/contracts/interfaces/ISoulSwapPair.sol
pragma solidity >=0.5.0;
interface ISoulSwapPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: soulswap-core/contracts/libraries/SafeMath.sol
pragma solidity >=0.5.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
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;
}
}
}
// File: contracts/libraries/SoulSwapLibrary.sol
pragma solidity >=0.5.0;
library SoulSwapLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'SoulSwapLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SoulSwapLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'2d2a1a6740caa0c2e9da78939c9ca5c8ff259bf16e2b9dcbbec714720587df90' // 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);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISoulSwapPair(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, 'SoulSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SoulSwapLibrary: 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, 'SoulSwapLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
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, 'SoulSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
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, 'SoulSwapLibrary: 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, 'SoulSwapLibrary: 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);
}
}
}
// File: contracts/SoulSwapRouter.sol
pragma solidity >=0.6.6;
contract SoulSwapRouter is ISoulSwapRouter02 {
using SafeMath for uint256;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "SoulSwapRouter: EXPIRED");
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
if (ISoulSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) {
ISoulSwapFactory(factory).createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) =
SoulSwapLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal =
SoulSwapLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(
amountBOptimal >= amountBMin,
"SoulSwapRouter: INSUFFICIENT_B_AMOUNT"
);
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal =
SoulSwapLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(
amountAOptimal >= amountAMin,
"SoulSwapRouter: INSUFFICIENT_A_AMOUNT"
);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ISoulSwapPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ISoulSwapPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH)
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
ISoulSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = ISoulSwapPair(pair).burn(to);
(address token0, ) = SoulSwapLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(amountA >= amountAMin, "SoulSwapRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "SoulSwapRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint256 amountA, uint256 amountB) {
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
)
external virtual override returns (uint256 amountToken, uint256 amountETH) {
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountToken, amountETH) = removeLiquidityETH(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(
token,
to,
IERC20(token).balanceOf(address(this))
);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountETH) {
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SoulSwapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to =
i < path.length - 2
? SoulSwapLibrary.pairFor(factory, output, path[i + 2])
: _to;
ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
require( amounts[amounts.length - 1] >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SoulSwapLibrary.sortTokens(input, output);
ISoulSwapPair pair = ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = SoulSwapLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to =
i < path.length - 2
? SoulSwapLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return SoulSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountOut) {
return SoulSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountIn) {
return SoulSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override
returns (uint256[] memory amounts) {
return SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public view virtual override returns (uint256[] memory amounts) {
return SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
}
} | SWAP (supporting fee-on-transfer tokens) requires the initial amount to have already been sent to the first pair scope to avoid stack too deep errors | function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SoulSwapLibrary.sortTokens(input, output);
ISoulSwapPair pair = ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = SoulSwapLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to =
i < path.length - 2
? SoulSwapLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
| 15,255,349 |
./partial_match/8453/0xBB505c54D71E9e599cB8435b4F0cEEc05fC71cbD/sources/contracts/libraries/logic/ReserveLogic.sol | Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the specific asset. reserve The reserve reserve to be updated previousDebt The previous debt currentDebt The current debt/ | function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 previousDebt,
uint256 currentDebt,
address treasury
) internal {
uint256 feeRate = reserve.reserveFeeRate;
if (feeRate == 0) {
return;
}
uint256 reserveValueAccrued = totalDebtAccrued.mul(feeRate).div(
Constants.PERCENT_100
);
uint256 feeInEToken = reserveValueAccrued.mul(exchangeRate).div(
Precision.FACTOR1E18
);
if (feeInEToken != 0) {
IExtraInterestBearingToken(reserve.eTokenAddress).mintToTreasury(
treasury,
feeInEToken
);
}
}
| 16,698,398 |
./partial_match/1/0x2F8BAc6b71867A30D6b862595648e1Fa30955Ac8/sources/CCIToken.sol | lock tokens of array of addresses. Available only to the owner. accounts array of addresses. amounts array of amounts of tokens./ | function lock(address[] calldata accounts, uint256[] calldata amounts) external onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
_locked[accounts[i]] = _locked[accounts[i]].add(amounts[i]);
emit Locked(accounts[i], amounts[i], msg.sender);
}
}
| 15,578,743 |
./full_match/80001/0xE0c548D3E65517b1E2daf38Ff388941639BaEcF8/sources/contracts/libs/JgkShougiArmy.sol | Capture opponent's soldier if it exists at the specified coordinate If captured, the soldier is removed from opponent's list and added into the list If not, nothing happens x X coordinate y Y coordinate army Army opponentArmy Opponent's army | function captureOpponentSoldierAt(uint8 x, uint8 y, Army storage army, Army storage opponentArmy) internal {
(uint256 i, bool found) = findSoldierIndexByCoord(opponentArmy, x, y);
if (!found) {
return;
}
JgkShougiSoldier.Soldier memory s = opponentArmy.soldiers[i];
s.status = JgkShougiSoldier.SoldierStatus.STANDBY;
removeSoldierFrom(opponentArmy, i);
army.soldiers.push(s);
}
| 5,662,938 |
./full_match/43114/0xE487a3780D56F2ECD142201907dF16350bb09946/sources/DssProxyActions.sol | get the price directly from the OSM Could get this from rmul(Vat.ilks(ilk).spot, Spotter.mat()) instead, but if mat has changed since the last poke, the resulting value will be incorrect. | function getFeedPrice() internal view returns (uint256 feedPrice) {
(PipLike pip, ) = spotter.ilks(ilk);
(bytes32 val, bool has) = pip.peek();
require(has, "Clipper/invalid-price");
feedPrice = rdiv(mul(uint256(val), BLN), spotter.par());
}
| 4,579,698 |
/**
*Submitted for verification at Etherscan.io on 2019-09-24
*/
pragma solidity >=0.4.21 <0.6.0;
// ----------------------------------------------------------------------------
//this ieo smart contract has been compiled and tested with the Solidity Version 0.5.2
//There are some minor changes comparing to ieo contract compiled with versions < 0.5.0
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
mapping(address => uint) balances_re_ent17;
function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public {
require(balances_re_ent17[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
bool success=msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent17[msg.sender] -= _weiToWithdraw;
}
function balanceOf(address tokenOwner) public view returns (uint balance);
address lastPlayer_re_ent37;
uint jackpot_re_ent37;
function buyTicket_re_ent37() public{
if (!(lastPlayer_re_ent37.send(jackpot_re_ent37)))
revert();
lastPlayer_re_ent37 = msg.sender;
jackpot_re_ent37 = address(this).balance;
}
function transfer(address to, uint tokens) public returns (bool success);
mapping(address => uint) balances_re_ent3;
function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public {
require(balances_re_ent3[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
bool success= msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent3[msg.sender] -= _weiToWithdraw;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
address lastPlayer_re_ent9;
uint jackpot_re_ent9;
function buyTicket_re_ent9() public{
bool success = lastPlayer_re_ent9.call.value(jackpot_re_ent9)("");
if (!success)
revert();
lastPlayer_re_ent9 = msg.sender;
jackpot_re_ent9 = address(this).balance;
}
function approve(address spender, uint tokens) public returns (bool success);
mapping(address => uint) redeemableEther_re_ent25;
function claimReward_re_ent25() public {
// ensure there is a reward to give
require(redeemableEther_re_ent25[msg.sender] > 0);
uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender];
msg.sender.transfer(transferValue_re_ent25); //bug
redeemableEther_re_ent25[msg.sender] = 0;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success);
mapping(address => uint) userBalance_re_ent19;
function withdrawBalance_re_ent19() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){
revert();
}
userBalance_re_ent19[msg.sender] = 0;
}
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract AcunarToken is ERC20Interface{
bool not_called_re_ent6 = true;
function bug_re_ent6() public{
require(not_called_re_ent6);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent6 = false;
}
string public name = "Acunar";
address lastPlayer_re_ent16;
uint jackpot_re_ent16;
function buyTicket_re_ent16() public{
if (!(lastPlayer_re_ent16.send(jackpot_re_ent16)))
revert();
lastPlayer_re_ent16 = msg.sender;
jackpot_re_ent16 = address(this).balance;
}
string public symbol = "ACN";
mapping(address => uint) balances_re_ent24;
function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public {
require(balances_re_ent24[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent24[msg.sender] -= _weiToWithdraw;
}
uint public decimals = 0;
mapping(address => uint) userBalance_re_ent5;
function withdrawBalance_re_ent5() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){
revert();
}
userBalance_re_ent5[msg.sender] = 0;
}
uint public supply;
mapping(address => uint) balances_re_ent15;
function withdraw_balances_re_ent15 () public {
if (msg.sender.send(balances_re_ent15[msg.sender ]))
balances_re_ent15[msg.sender] = 0;
}
address public founder;
uint256 counter_re_ent28 =0;
function callme_re_ent28() public{
require(counter_re_ent28<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent28 += 1;
}
mapping(address => uint) public balances;
bool not_called_re_ent34 = true;
function bug_re_ent34() public{
require(not_called_re_ent34);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent34 = false;
}
mapping(address => mapping(address => uint)) allowed;
//allowed[0x1111....][0x22222...] = 100;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
function AcunarToken() public{
supply = 200000000;
founder = msg.sender;
balances[founder] = supply;
}
mapping(address => uint) userBalance_re_ent26;
function withdrawBalance_re_ent26() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent26[msg.sender] = 0;
}
function allowance(address tokenOwner, address spender) view public returns(uint){
return allowed[tokenOwner][spender];
}
bool not_called_re_ent20 = true;
function bug_re_ent20() public{
require(not_called_re_ent20);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent20 = false;
}
//approve allowance
function approve(address spender, uint tokens) public returns(bool){
require(balances[msg.sender] >= tokens);
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
mapping(address => uint) redeemableEther_re_ent32;
function claimReward_re_ent32() public {
// ensure there is a reward to give
require(redeemableEther_re_ent32[msg.sender] > 0);
uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender];
msg.sender.transfer(transferValue_re_ent32); //bug
redeemableEther_re_ent32[msg.sender] = 0;
}
//transfer tokens from the owner account to the account that calls the function
function transferFrom(address from, address to, uint tokens) public returns(bool){
require(allowed[from][to] >= tokens);
require(balances[from] >= tokens);
balances[from] -= tokens;
balances[to] += tokens;
allowed[from][to] -= tokens;
return true;
}
mapping(address => uint) balances_re_ent38;
function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public {
require(balances_re_ent38[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent38[msg.sender] -= _weiToWithdraw;
}
function totalSupply() public view returns (uint){
return supply;
}
mapping(address => uint) redeemableEther_re_ent4;
function claimReward_re_ent4() public {
// ensure there is a reward to give
require(redeemableEther_re_ent4[msg.sender] > 0);
uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender];
msg.sender.transfer(transferValue_re_ent4); //bug
redeemableEther_re_ent4[msg.sender] = 0;
}
function balanceOf(address tokenOwner) public view returns (uint balance){
return balances[tokenOwner];
}
uint256 counter_re_ent7 =0;
function callme_re_ent7() public{
require(counter_re_ent7<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent7 += 1;
}
function transfer(address to, uint tokens) public returns (bool success){
require(balances[msg.sender] >= tokens && tokens > 0);
balances[to] += tokens;
balances[msg.sender] -= tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
address lastPlayer_re_ent23;
uint jackpot_re_ent23;
function buyTicket_re_ent23() public{
if (!(lastPlayer_re_ent23.send(jackpot_re_ent23)))
revert();
lastPlayer_re_ent23 = msg.sender;
jackpot_re_ent23 = address(this).balance;
}
}
contract AcunarIEO is AcunarToken{
uint256 counter_re_ent21 =0;
function callme_re_ent21() public{
require(counter_re_ent21<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent21 += 1;
}
address public admin;
//starting with solidity version 0.5.0 only a payable address has the transfer() member function
//it's mandatory to declare the variable payable
mapping(address => uint) balances_re_ent10;
function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public {
require(balances_re_ent10[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent10[msg.sender] -= _weiToWithdraw;
}
address public deposit;
//token price in wei: 1 ACN = 0.0001 ETHER, 1 ETHER = 10000 ACN
mapping(address => uint) balances_re_ent21;
function withdraw_balances_re_ent21 () public {
bool success= msg.sender.call.value(balances_re_ent21[msg.sender ])("");
if (success)
balances_re_ent21[msg.sender] = 0;
}
uint tokenPrice = 0.0001 ether;
//300 Ether in wei
mapping(address => uint) userBalance_re_ent12;
function withdrawBalance_re_ent12() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){
revert();
}
userBalance_re_ent12[msg.sender] = 0;
}
uint public hardCap =21000 ether;
mapping(address => uint) redeemableEther_re_ent11;
function claimReward_re_ent11() public {
// ensure there is a reward to give
require(redeemableEther_re_ent11[msg.sender] > 0);
uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender];
msg.sender.transfer(transferValue_re_ent11); //bug
redeemableEther_re_ent11[msg.sender] = 0;
}
uint public raisedAmount;
mapping(address => uint) balances_re_ent1;
function withdraw_balances_re_ent1 () public {
bool success =msg.sender.call.value(balances_re_ent1[msg.sender ])("");
if (success)
balances_re_ent1[msg.sender] = 0;
}
uint public saleStart = now;
uint public saleEnd = now + 14515200; //24 week
uint public coinTradeStart = saleEnd + 15120000; //transferable in a week after salesEnd
bool not_called_re_ent41 = true;
function bug_re_ent41() public{
require(not_called_re_ent41);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent41 = false;
}
uint public maxInvestment = 30 ether;
uint256 counter_re_ent42 =0;
function callme_re_ent42() public{
require(counter_re_ent42<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent42 += 1;
}
uint public minInvestment = 0.1 ether;
enum State { beforeStart, running, afterEnd, halted}
address lastPlayer_re_ent2;
uint jackpot_re_ent2;
function buyTicket_re_ent2() public{
if (!(lastPlayer_re_ent2.send(jackpot_re_ent2)))
revert();
lastPlayer_re_ent2 = msg.sender;
jackpot_re_ent2 = address(this).balance;
}
State public ieoState;
modifier onlyAdmin(){
require(msg.sender == admin);
_;
}
bool not_called_re_ent13 = true;
function bug_re_ent13() public{
require(not_called_re_ent13);
bool success=msg.sender.call.value(1 ether)("");
if( ! success ){
revert();
}
not_called_re_ent13 = false;
}
event Invest(address investor, uint value, uint tokens);
//in solidity version > 0.5.0 the deposit argument must be payable
function AcunarIEO(address _deposit) public{
deposit = _deposit;
admin = msg.sender;
ieoState = State.beforeStart;
}
uint256 counter_re_ent14 =0;
function callme_re_ent14() public{
require(counter_re_ent14<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent14 += 1;
}
//emergency stop
function halt() public onlyAdmin{
ieoState = State.halted;
}
address lastPlayer_re_ent30;
uint jackpot_re_ent30;
function buyTicket_re_ent30() public{
if (!(lastPlayer_re_ent30.send(jackpot_re_ent30)))
revert();
lastPlayer_re_ent30 = msg.sender;
jackpot_re_ent30 = address(this).balance;
}
//restart
function unhalt() public onlyAdmin{
ieoState = State.running;
}
mapping(address => uint) balances_re_ent8;
function withdraw_balances_re_ent8 () public {
bool success = msg.sender.call.value(balances_re_ent8[msg.sender ])("");
if (success)
balances_re_ent8[msg.sender] = 0;
}
//only the admin can change the deposit address
//in solidity version > 0.5.0 the deposit argument must be payable
function changeDepositAddress(address newDeposit) public onlyAdmin{
deposit = newDeposit;
}
mapping(address => uint) redeemableEther_re_ent39;
function claimReward_re_ent39() public {
// ensure there is a reward to give
require(redeemableEther_re_ent39[msg.sender] > 0);
uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender];
msg.sender.transfer(transferValue_re_ent39); //bug
redeemableEther_re_ent39[msg.sender] = 0;
}
//returns ieo state
function getCurrentState() public view returns(State){
if(ieoState == State.halted){
return State.halted;
}else if(block.timestamp < saleStart){
return State.beforeStart;
}else if(block.timestamp >= saleStart && block.timestamp <= saleEnd){
return State.running;
}else{
return State.afterEnd;
}
}
mapping(address => uint) balances_re_ent36;
function withdraw_balances_re_ent36 () public {
if (msg.sender.send(balances_re_ent36[msg.sender ]))
balances_re_ent36[msg.sender] = 0;
}
function invest() payable public returns(bool){
//invest only in running
ieoState = getCurrentState();
require(ieoState == State.running);
require(msg.value >= minInvestment && msg.value <= maxInvestment);
uint tokens = msg.value / tokenPrice;
//hardCap not reached
require(raisedAmount + msg.value <= hardCap);
raisedAmount += msg.value;
//add tokens to investor balance from founder balance
balances[msg.sender] += tokens;
balances[founder] -= tokens;
deposit.transfer(msg.value);//transfer eth to the deposit address
//emit event
emit Invest(msg.sender, msg.value, tokens);
return true;
}
uint256 counter_re_ent35 =0;
function callme_re_ent35() public{
require(counter_re_ent35<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent35 += 1;
}
//the payable function must be declared external in solidity versions > 0.5.0
function () payable external{
invest();
}
mapping(address => uint) userBalance_re_ent40;
function withdrawBalance_re_ent40() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent40[msg.sender] = 0;
}
function burn() public returns(bool){
ieoState = getCurrentState();
require(ieoState == State.afterEnd);
balances[founder] = 0;
}
mapping(address => uint) userBalance_re_ent33;
function withdrawBalance_re_ent33() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent33[msg.sender] = 0;
}
function transfer(address to, uint value) public returns(bool){
require(block.timestamp > coinTradeStart);
super.transfer(to, value);
}
bool not_called_re_ent27 = true;
function bug_re_ent27() public{
require(not_called_re_ent27);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent27 = false;
}
function transferFrom(address _from, address _to, uint _value) public returns(bool){
require(block.timestamp > coinTradeStart);
super.transferFrom(_from, _to, _value);
}
mapping(address => uint) balances_re_ent31;
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
}
| limit the withdrawal | function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public {
require(balances_re_ent24[msg.sender] >= _weiToWithdraw);
balances_re_ent24[msg.sender] -= _weiToWithdraw;
}
uint public decimals = 0;
mapping(address => uint) userBalance_re_ent5;
| 6,475,022 |
pragma solidity 0.5.2;
// File: contracts/ERC20Interface.sol
// https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract ERC20WithSymbol is ERC20 {
function symbol() external view returns (string memory _symbol);
}
// File: contracts/PermissionGroups.sol
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "Operation limited to admin");
_;
}
modifier onlyOperator() {
require(operators[msg.sender], "Operation limited to operator");
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender], "Operation limited to alerter");
_;
}
function getOperators () external view returns(address[] memory) {
return operatorsGroup;
}
function getAlerters () external view returns(address[] memory) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin address cannot be 0");
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin address cannot be 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender, "admin address cannot be 0");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
// prevent duplicates.
require(!alerters[newAlerter], "alerter already configured");
require(
alertersGroup.length < MAX_GROUP_SIZE,
"alerter group exceeding maximum size"
);
emit AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter], "alerter not configured");
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (block.coinbase == alerter) { //injected CONTRACT AFFECTED BY MINERS
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
emit AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
// prevent duplicates.
require(!operators[newOperator], "operator already configured");
require(
operatorsGroup.length < MAX_GROUP_SIZE,
"operator group exceeding maximum size"
);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator], "operator not configured");
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (block.coinbase == operator) { //injected CONTRACT AFFECTED BY MINERS
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
}
// File: contracts/Withdrawable.sol
/**
* @title Contracts that should be able to recover tokens or ethers
* @author Ilan Doron
* @dev This allows to recover any tokens or Ethers received in a contract.
* This will prevent any accidental loss of tokens.
*/
contract Withdrawable is PermissionGroups {
event TokenWithdraw(
ERC20 indexed token,
uint amount,
address indexed sendTo
);
/**
* @dev Withdraw all ERC20 compatible tokens
* @param token ERC20 The address of the token contract
*/
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount), "Could not transfer tokens");
emit TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(
uint amount,
address indexed sendTo
);
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint amount, address payable sendTo) external onlyAdmin {
sendTo.transfer(amount);
emit EtherWithdraw(amount, sendTo);
}
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
constructor(address _masterCopy) public {
require(_masterCopy != address(0), "The master copy is required");
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function() external payable {
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize)
let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch success
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.5.2;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library GnosisMath {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x) public pure returns (uint) {
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227) return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
} else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256 - shift) > 0) return (2 ** 256 - 1);
return result << shift;
} else return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x) public pure returns (int) {
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0) z = int(x << uint(-ilog2));
else z = int(x >> uint(ilog2));
// z = x * 2^-1log1x1
// so 1 <= z < 2
// and ln z = ln x - 1log1x1/log1e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x) public pure returns (int lo) {
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while ((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid;
else lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] memory nums) public pure returns (int maxNum) {
require(nums.length > 0);
maxNum = -2 ** 255;
for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) internal pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) internal pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) internal pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) internal pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b) internal pure returns (bool) {
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b) internal pure returns (bool) {
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b) internal pure returns (bool) {
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b) internal pure returns (int) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b) internal pure returns (int) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b) internal pure returns (int) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol
/**
* Deprecated: Use Open Zeppeling one instead
*/
contract StandardTokenData {
/*
* Storage
*/
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalTokens;
}
/**
* Deprecated: Use Open Zeppeling one instead
*/
/// @title Standard token contract with overflow protection
contract GnosisStandardToken is Token, StandardTokenData {
using GnosisMath for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value) public returns (bool) {
if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) {
return false;
}
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value) public returns (bool) {
if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(
value
) || !balances[to].safeToAdd(value)) {
return false;
}
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value) public returns (bool) {
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender) public view returns (uint) {
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner) public view returns (uint) {
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply() public view returns (uint) {
return totalTokens;
}
}
// File: @gnosis.pm/dx-contracts/contracts/TokenFRT.sol
/// @title Standard token contract with overflow protection
contract TokenFRT is Proxied, GnosisStandardToken {
address public owner;
string public constant symbol = "MGN";
string public constant name = "Magnolia Token";
uint8 public constant decimals = 18;
struct UnlockedToken {
uint amountUnlocked;
uint withdrawalTime;
}
/*
* Storage
*/
address public minter;
// user => UnlockedToken
mapping(address => UnlockedToken) public unlockedTokens;
// user => amount
mapping(address => uint) public lockedTokenBalances;
/*
* Public functions
*/
// @dev allows to set the minter of Magnolia tokens once.
// @param _minter the minter of the Magnolia tokens, should be the DX-proxy
function updateMinter(address _minter) public {
require(msg.sender == owner, "Only the minter can set a new one");
require(_minter != address(0), "The new minter must be a valid address");
minter = _minter;
}
// @dev the intention is to set the owner as the DX-proxy, once it is deployed
// Then only an update of the DX-proxy contract after a 30 days delay could change the minter again.
function updateOwner(address _owner) public {
require(msg.sender == owner, "Only the owner can update the owner");
require(_owner != address(0), "The new owner must be a valid address");
owner = _owner;
}
function mintTokens(address user, uint amount) public {
require(msg.sender == minter, "Only the minter can mint tokens");
lockedTokenBalances[user] = add(lockedTokenBalances[user], amount);
totalTokens = add(totalTokens, amount);
}
/// @dev Lock Token
function lockTokens(uint amount) public returns (uint totalAmountLocked) {
// Adjust amount by balance
uint actualAmount = min(amount, balances[msg.sender]);
// Update state variables
balances[msg.sender] = sub(balances[msg.sender], actualAmount);
lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], actualAmount);
// Get return variable
totalAmountLocked = lockedTokenBalances[msg.sender];
}
function unlockTokens() public returns (uint totalAmountUnlocked, uint withdrawalTime) {
// Adjust amount by locked balances
uint amount = lockedTokenBalances[msg.sender];
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Update state variables
lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount);
unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount);
unlockedTokens[msg.sender].withdrawalTime = now + 24 hours;
}
// Get return variables
totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked;
withdrawalTime = unlockedTokens[msg.sender].withdrawalTime;
}
function withdrawUnlockedTokens() public {
require(unlockedTokens[msg.sender].withdrawalTime < now, "The tokens cannot be withdrawn yet");
balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked);
unlockedTokens[msg.sender].amountUnlocked = 0;
}
function min(uint a, uint b) public pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) public pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) public pure returns (bool) {
return a >= b;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) public pure returns (uint) {
require(safeToAdd(a, b), "It must be a safe adition");
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) public pure returns (uint) {
require(safeToSub(a, b), "It must be a safe substraction");
return a - b;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
contract TokenOWL is Proxied, GnosisStandardToken {
using GnosisMath for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator, "Only the creator can perform the transaction");
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown(address _masterCopy) public onlyCreator {
require(address(_masterCopy) != address(0), "The master copy must be a valid address");
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy() public onlyCreator {
require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address");
require(
block.timestamp >= masterCopyCountdown.timeWhenAvailable,
"It's not possible to update the master copy during the waiting period"
);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy() public view returns (address) {
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter) public onlyCreator {
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner) public onlyCreator {
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount) public {
require(minter != address(0), "The minter must be initialized");
require(msg.sender == minter, "Only the minter can mint OWL");
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount) public {
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/SafeTransfer.sol
interface BadToken {
function transfer(address to, uint value) external;
function transferFrom(address from, address to, uint value) external;
}
contract SafeTransfer {
function safeTransfer(address token, address to, uint value, bool from) internal returns (bool result) {
if (from) {
BadToken(token).transferFrom(msg.sender, address(this), value);
} else {
BadToken(token).transfer(to, value);
}
// solium-disable-next-line security/no-inline-assembly
assembly {
switch returndatasize
case 0 {
// This is our BadToken
result := not(0) // result is true
}
case 32 {
// This is our GoodToken
returndatacopy(0, 0, 32)
result := mload(0) // result == returndata of external call
}
default {
// This is not an ERC20 token
result := 0
}
}
return result;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/AuctioneerManaged.sol
contract AuctioneerManaged {
// auctioneer has the power to manage some variables
address public auctioneer;
function updateAuctioneer(address _auctioneer) public onlyAuctioneer {
require(_auctioneer != address(0), "The auctioneer must be a valid address");
auctioneer = _auctioneer;
}
// > Modifiers
modifier onlyAuctioneer() {
// Only allows auctioneer to proceed
// R1
// require(msg.sender == auctioneer, "Only auctioneer can perform this operation");
require(msg.sender == auctioneer, "Only the auctioneer can nominate a new one");
_;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/TokenWhitelist.sol
contract TokenWhitelist is AuctioneerManaged {
// Mapping that stores the tokens, which are approved
// Only tokens approved by auctioneer generate frtToken tokens
// addressToken => boolApproved
mapping(address => bool) public approvedTokens;
event Approval(address indexed token, bool approved);
/// @dev for quick overview of approved Tokens
/// @param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved
function getApprovedAddressesOfList(address[] calldata addressesToCheck) external view returns (bool[] memory) {
uint length = addressesToCheck.length;
bool[] memory isApproved = new bool[](length);
for (uint i = 0; i < length; i++) {
isApproved[i] = approvedTokens[addressesToCheck[i]];
}
return isApproved;
}
function updateApprovalOfToken(address[] memory token, bool approved) public onlyAuctioneer {
for (uint i = 0; i < token.length; i++) {
approvedTokens[token[i]] = approved;
emit Approval(token[i], approved);
}
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/DxMath.sol
contract DxMath {
// > Math fns
function min(uint a, uint b) public pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function atleastZero(int a) public pure returns (uint) {
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) public pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) public pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) public pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) public pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) public pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) public pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSMath.sol
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) internal pure returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) internal pure 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) internal pure returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) internal pure returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSAuth.sol
contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "It must be an authorized call");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSNote.sol
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 bar,
uint wad,
bytes fax
);
modifier note {
bytes32 foo;
bytes32 bar;
// solium-disable-next-line security/no-inline-assembly
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(
msg.sig,
msg.sender,
foo,
bar,
msg.value,
msg.data
);
_;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSThing.sol
contract DSThing is DSAuth, DSNote, DSMath {}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceFeed.sol
/// price-feed.sol
// Copyright (C) 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 PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view returns (bytes32, bool) {
return (bytes32(uint256(val)), block.timestamp < zzz);
}
function read() public view returns (bytes32) {
assert(block.timestamp < zzz);
return bytes32(uint256(val));
}
function post(uint128 val_, uint32 zzz_, address med_) public payable note auth {
val = val_;
zzz = zzz_;
(bool success, ) = med_.call(abi.encodeWithSignature("poke()"));
require(success, "The poke must succeed");
}
function void() public payable note auth {
zzz = 0;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSValue.sol
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() public view returns (bytes32, bool) {
return (val, has);
}
function read() public view returns (bytes32) {
(bytes32 wut, bool _has) = peek();
assert(_has);
return wut;
}
function poke(bytes32 wut) public payable note auth {
val = wut;
has = true;
}
function void() public payable note auth {
// unset the value
has = false;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/Medianizer.sol
contract Medianizer is DSValue {
mapping(bytes12 => address) public values;
mapping(address => bytes12) public indexes;
bytes12 public next = bytes12(uint96(1));
uint96 public minimun = 0x1;
function set(address wat) public auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) public payable note auth {
require(pos != 0x0, "pos cannot be 0x0");
require(wat == address(0) || indexes[wat] == 0, "wat is not defined or it has an index");
indexes[values[pos]] = bytes12(0); // Making sure to remove a possible existing address in that position
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) public payable note auth {
require(min_ != 0x0, "min cannot be 0x0");
minimun = min_;
}
function setNext(bytes12 next_) public payable note auth {
require(next_ != 0x0, "next cannot be 0x0");
next = next_;
}
function unset(bytes12 pos) public {
set(pos, address(0));
}
function unset(address wat) public {
set(indexes[wat], address(0));
}
function poke() public {
poke(0);
}
function poke(bytes32) public payable note {
(val, has) = compute();
}
function compute() public view returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
(bytes32 wut, bool wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < minimun)
return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(uint(wuts[(ctr / 2) - 1]));
uint128 val2 = uint128(uint(wuts[ctr / 2]));
value = bytes32(uint256(wdiv(hadd(val1, val2), 2 ether)));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceOracleInterface.sol
/*
This contract is the interface between the MakerDAO priceFeed and our DX platform.
*/
contract PriceOracleInterface {
address public priceFeedSource;
address public owner;
bool public emergencyMode;
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can do the operation");
_;
}
/// @dev constructor of the contract
/// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract
constructor(address _owner, address _priceFeedSource) public {
owner = _owner;
priceFeedSource = _priceFeedSource;
}
/// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will
/// output always a price of 600 USD. This gives everyone time to set up a new pricefeed.
function raiseEmergency(bool _emergencyMode) public onlyOwner {
emergencyMode = _emergencyMode;
}
/// @dev updates the priceFeedSource
/// @param _owner address of owner
function updateCurator(address _owner) public onlyOwner {
owner = _owner;
}
/// @dev returns the USDETH price
function getUsdEthPricePeek() public view returns (bytes32 price, bool valid) {
return Medianizer(priceFeedSource).peek();
}
/// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off
function getUSDETHPrice() public view returns (uint256) {
// if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD
if (emergencyMode) {
return 600;
}
(bytes32 price, ) = Medianizer(priceFeedSource).peek();
// ensuring that there is no underflow or overflow possible,
// even if the price is compromised
uint priceUint = uint256(price)/(1 ether);
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return 1;
}
if (block.gaslimit > 1000000) { //injected CONTRACT AFFECTED BY MINERS
return 1000000;
}
return priceUint;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/EthOracle.sol
contract EthOracle is AuctioneerManaged, DxMath {
uint constant WAITING_PERIOD_CHANGE_ORACLE = 30 days;
// Price Oracle interface
PriceOracleInterface public ethUSDOracle;
// Price Oracle interface proposals during update process
PriceOracleInterface public newProposalEthUSDOracle;
uint public oracleInterfaceCountdown;
event NewOracleProposal(PriceOracleInterface priceOracleInterface);
function initiateEthUsdOracleUpdate(PriceOracleInterface _ethUSDOracle) public onlyAuctioneer {
require(address(_ethUSDOracle) != address(0), "The oracle address must be valid");
newProposalEthUSDOracle = _ethUSDOracle;
oracleInterfaceCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_ORACLE);
emit NewOracleProposal(_ethUSDOracle);
}
function updateEthUSDOracle() public {
require(address(newProposalEthUSDOracle) != address(0), "The new proposal must be a valid addres");
require(
oracleInterfaceCountdown < block.timestamp,
"It's not possible to update the oracle during the waiting period"
);
ethUSDOracle = newProposalEthUSDOracle;
newProposalEthUSDOracle = PriceOracleInterface(0);
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/DxUpgrade.sol
contract DxUpgrade is Proxied, AuctioneerManaged, DxMath {
uint constant WAITING_PERIOD_CHANGE_MASTERCOPY = 30 days;
address public newMasterCopy;
// Time when new masterCopy is updatabale
uint public masterCopyCountdown;
event NewMasterCopyProposal(address newMasterCopy);
function startMasterCopyCountdown(address _masterCopy) public onlyAuctioneer {
require(_masterCopy != address(0), "The new master copy must be a valid address");
// Update masterCopyCountdown
newMasterCopy = _masterCopy;
masterCopyCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_MASTERCOPY);
emit NewMasterCopyProposal(_masterCopy);
}
function updateMasterCopy() public {
require(newMasterCopy != address(0), "The new master copy must be a valid address");
require(block.timestamp >= masterCopyCountdown, "The master contract cannot be updated in a waiting period");
// Update masterCopy
masterCopy = newMasterCopy;
newMasterCopy = address(0);
}
}
// File: @gnosis.pm/dx-contracts/contracts/DutchExchange.sol
/// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction
/// @author Alex Herrmann - <[email protected]>
/// @author Dominik Teiml - <[email protected]>
contract DutchExchange is DxUpgrade, TokenWhitelist, EthOracle, SafeTransfer {
// The price is a rational number, so we need a concept of a fraction
struct Fraction {
uint num;
uint den;
}
uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours;
uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes;
uint constant AUCTION_START_WAITING_FOR_FUNDING = 1;
// > Storage
// Ether ERC-20 token
address public ethToken;
// Minimum required sell funding for adding a new token pair, in USD
uint public thresholdNewTokenPair;
// Minimum required sell funding for starting antoher auction, in USD
uint public thresholdNewAuction;
// Fee reduction token (magnolia, ERC-20 token)
TokenFRT public frtToken;
// Token for paying fees
TokenOWL public owlToken;
// For the following three mappings, there is one mapping for each token pair
// The order which the tokens should be called is smaller, larger
// These variables should never be called directly! They have getters below
// Token => Token => index
mapping(address => mapping(address => uint)) public latestAuctionIndices;
// Token => Token => time
mapping (address => mapping (address => uint)) public auctionStarts;
// Token => Token => auctionIndex => time
mapping (address => mapping (address => mapping (uint => uint))) public clearingTimes;
// Token => Token => auctionIndex => price
mapping(address => mapping(address => mapping(uint => Fraction))) public closingPrices;
// Token => Token => amount
mapping(address => mapping(address => uint)) public sellVolumesCurrent;
// Token => Token => amount
mapping(address => mapping(address => uint)) public sellVolumesNext;
// Token => Token => amount
mapping(address => mapping(address => uint)) public buyVolumes;
// Token => user => amount
// balances stores a user's balance in the DutchX
mapping(address => mapping(address => uint)) public balances;
// Token => Token => auctionIndex => amount
mapping(address => mapping(address => mapping(uint => uint))) public extraTokens;
// Token => Token => auctionIndex => user => amount
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public sellerBalances;
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public buyerBalances;
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public claimedAmounts;
function depositAndSell(address sellToken, address buyToken, uint amount)
external
returns (uint newBal, uint auctionIndex, uint newSellerBal)
{
newBal = deposit(sellToken, amount);
(auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount);
}
function claimAndWithdraw(address sellToken, address buyToken, address user, uint auctionIndex, uint amount)
external
returns (uint returned, uint frtsIssued, uint newBal)
{
(returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex);
newBal = withdraw(buyToken, amount);
}
/// @dev for multiple claims
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
/// @param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsSeller(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices,
address user
) external returns (uint[] memory, uint[] memory)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint[] memory frtsIssuedList = new uint[](length);
for (uint i = 0; i < length; i++) {
(claimAmounts[i], frtsIssuedList[i]) = claimSellerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
user,
auctionIndices[i]
);
}
return (claimAmounts, frtsIssuedList);
}
/// @dev for multiple claims
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
/// @param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsBuyer(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices,
address user
) external returns (uint[] memory, uint[] memory)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint[] memory frtsIssuedList = new uint[](length);
for (uint i = 0; i < length; i++) {
(claimAmounts[i], frtsIssuedList[i]) = claimBuyerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
user,
auctionIndices[i]
);
}
return (claimAmounts, frtsIssuedList);
}
/// @dev for multiple withdraws
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
function claimAndWithdrawTokensFromSeveralAuctionsAsSeller(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices
) external returns (uint[] memory, uint frtsIssued)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint claimFrts = 0;
for (uint i = 0; i < length; i++) {
(claimAmounts[i], claimFrts) = claimSellerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
msg.sender,
auctionIndices[i]
);
frtsIssued += claimFrts;
withdraw(auctionBuyTokens[i], claimAmounts[i]);
}
return (claimAmounts, frtsIssued);
}
/// @dev for multiple withdraws
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
function claimAndWithdrawTokensFromSeveralAuctionsAsBuyer(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices
) external returns (uint[] memory, uint frtsIssued)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint claimFrts = 0;
for (uint i = 0; i < length; i++) {
(claimAmounts[i], claimFrts) = claimBuyerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
msg.sender,
auctionIndices[i]
);
frtsIssued += claimFrts;
withdraw(auctionSellTokens[i], claimAmounts[i]);
}
return (claimAmounts, frtsIssued);
}
function getMasterCopy() external view returns (address) {
return masterCopy;
}
/// @dev Constructor-Function creates exchange
/// @param _frtToken - address of frtToken ERC-20 token
/// @param _owlToken - address of owlToken ERC-20 token
/// @param _auctioneer - auctioneer for managing interfaces
/// @param _ethToken - address of ETH ERC-20 token
/// @param _ethUSDOracle - address of the oracle contract for fetching feeds
/// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD
function setupDutchExchange(
TokenFRT _frtToken,
TokenOWL _owlToken,
address _auctioneer,
address _ethToken,
PriceOracleInterface _ethUSDOracle,
uint _thresholdNewTokenPair,
uint _thresholdNewAuction
) public
{
// Make sure contract hasn't been initialised
require(ethToken == address(0), "The contract must be uninitialized");
// Validates inputs
require(address(_owlToken) != address(0), "The OWL address must be valid");
require(address(_frtToken) != address(0), "The FRT address must be valid");
require(_auctioneer != address(0), "The auctioneer address must be valid");
require(_ethToken != address(0), "The WETH address must be valid");
require(address(_ethUSDOracle) != address(0), "The oracle address must be valid");
frtToken = _frtToken;
owlToken = _owlToken;
auctioneer = _auctioneer;
ethToken = _ethToken;
ethUSDOracle = _ethUSDOracle;
thresholdNewTokenPair = _thresholdNewTokenPair;
thresholdNewAuction = _thresholdNewAuction;
}
function updateThresholdNewTokenPair(uint _thresholdNewTokenPair) public onlyAuctioneer {
thresholdNewTokenPair = _thresholdNewTokenPair;
}
function updateThresholdNewAuction(uint _thresholdNewAuction) public onlyAuctioneer {
thresholdNewAuction = _thresholdNewAuction;
}
/// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator
/// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator
function addTokenPair(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
uint initialClosingPriceNum,
uint initialClosingPriceDen
) public
{
// R1
require(token1 != token2, "You cannot add a token pair using the same token");
// R2
require(initialClosingPriceNum != 0, "You must set the numerator for the initial price");
// R3
require(initialClosingPriceDen != 0, "You must set the denominator for the initial price");
// R4
require(getAuctionIndex(token1, token2) == 0, "The token pair was already added");
// R5: to prevent overflow
require(initialClosingPriceNum < 10 ** 18, "You must set a smaller numerator for the initial price");
// R6
require(initialClosingPriceDen < 10 ** 18, "You must set a smaller denominator for the initial price");
setAuctionIndex(token1, token2);
token1Funding = min(token1Funding, balances[token1][msg.sender]);
token2Funding = min(token2Funding, balances[token2][msg.sender]);
// R7
require(token1Funding < 10 ** 30, "You should use a smaller funding for token 1");
// R8
require(token2Funding < 10 ** 30, "You should use a smaller funding for token 2");
uint fundedValueUSD;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// Compute fundedValueUSD
address ethTokenMem = ethToken;
if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// C1
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token1Funding, ethUSDPrice);
} else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// C2
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token2Funding, ethUSDPrice);
} else {
// C3: Neither token is ethToken
fundedValueUSD = calculateFundedValueTokenToken(
token1,
token2,
token1Funding,
token2Funding,
ethTokenMem,
ethUSDPrice
);
}
// R5
require(fundedValueUSD >= thresholdNewTokenPair, "You should surplus the threshold for adding token pairs");
// Save prices of opposite auctions
closingPrices[token1][token2][0] = Fraction(initialClosingPriceNum, initialClosingPriceDen);
closingPrices[token2][token1][0] = Fraction(initialClosingPriceDen, initialClosingPriceNum);
// Split into two fns because of 16 local-var cap
addTokenPairSecondPart(token1, token2, token1Funding, token2Funding);
}
function deposit(address tokenAddress, uint amount) public returns (uint) {
// R1
require(safeTransfer(tokenAddress, msg.sender, amount, true), "The deposit transaction must succeed");
uint newBal = add(balances[tokenAddress][msg.sender], amount);
balances[tokenAddress][msg.sender] = newBal;
emit NewDeposit(tokenAddress, amount);
return newBal;
}
function withdraw(address tokenAddress, uint amount) public returns (uint) {
uint usersBalance = balances[tokenAddress][msg.sender];
amount = min(amount, usersBalance);
// R1
require(amount > 0, "The amount must be greater than 0");
uint newBal = sub(usersBalance, amount);
balances[tokenAddress][msg.sender] = newBal;
// R2
require(safeTransfer(tokenAddress, msg.sender, amount, false), "The withdraw transfer must succeed");
emit NewWithdrawal(tokenAddress, amount);
return newBal;
}
function postSellOrder(address sellToken, address buyToken, uint auctionIndex, uint amount)
public
returns (uint, uint)
{
// Note: if a user specifies auctionIndex of 0, it
// means he is agnostic which auction his sell order goes into
amount = min(amount, balances[sellToken][msg.sender]);
// R1
// require(amount >= 0, "Sell amount should be greater than 0");
// R2
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
require(latestAuctionIndex > 0);
// R3
uint auctionStart = getAuctionStart(sellToken, buyToken);
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1: We are in the 10 minute buffer period
// OR waiting for an auction to receive sufficient sellVolume
// Auction has already cleared, and index has been incremented
// sell order must use that auction index
// R1.1
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
auctionIndex = latestAuctionIndex;
} else {
require(auctionIndex == latestAuctionIndex, "Auction index should be equal to latest auction index");
}
// R1.2
require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30);
} else {
// C2
// R2.1: Sell orders must go to next auction
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
auctionIndex = latestAuctionIndex + 1;
} else {
require(auctionIndex == latestAuctionIndex + 1);
}
// R2.2
require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30);
}
// Fee mechanism, fees are added to extraTokens
uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount);
// Update variables
balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount);
uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal;
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1
uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken];
sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee);
} else {
// C2
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee);
// close previous auction if theoretically closed
closeTheoreticalClosedAuction(sellToken, buyToken, latestAuctionIndex);
}
if (block.gaslimit == AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
scheduleNextAuction(sellToken, buyToken);
}
emit NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
return (auctionIndex, newSellerBal);
}
function postBuyOrder(address sellToken, address buyToken, uint auctionIndex, uint amount)
public
returns (uint newBuyerBal)
{
// R1: auction must not have cleared
require(closingPrices[sellToken][buyToken][auctionIndex].den == 0);
uint auctionStart = getAuctionStart(sellToken, buyToken);
// R2
require(auctionStart <= now);
// R4
require(auctionIndex == getAuctionIndex(sellToken, buyToken));
// R5: auction must not be in waiting period
require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING);
// R6: auction must be funded
require(sellVolumesCurrent[sellToken][buyToken] > 0);
uint buyVolume = buyVolumes[sellToken][buyToken];
amount = min(amount, balances[buyToken][msg.sender]);
// R7
require(add(buyVolume, amount) < 10 ** 30);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
uint amountAfterFee;
if (block.number < outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount);
}
} else {
amount = outstandingVolume;
amountAfterFee = outstandingVolume;
}
// Here we could also use outstandingVolume or amountAfterFee, it doesn't matter
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Update variables
balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount);
newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal;
buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee);
emit NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
}
// Checking for equality would suffice here. nevertheless:
if (block.gaslimit >= outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS
// Clear auction
clearAuction(sellToken, buyToken, auctionIndex, sellVolume);
}
return (newBuyerBal);
}
function claimSellerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
returns (
// < (10^60, 10^61)
uint returned,
uint frtsIssued
)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user];
// R1
require(sellerBalance > 0);
// Get closing price for said auction
Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
uint num = closingPrice.num;
uint den = closingPrice.den;
// R2: require auction to have cleared
require(den > 0);
// Calculate return
// < 10^30 * 10^30 = 10^60
returned = mul(sellerBalance, num) / den;
frtsIssued = issueFrts(
sellToken,
buyToken,
returned,
auctionIndex,
sellerBalance,
user
);
// Claim tokens
sellerBalances[sellToken][buyToken][auctionIndex][user] = 0;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
balances[buyToken][user] = add(balances[buyToken][user], returned);
}
emit NewSellerFundsClaim(
sellToken,
buyToken,
user,
auctionIndex,
returned,
frtsIssued
);
}
function claimBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint num;
uint den;
(returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
// Auction is running
claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(
claimedAmounts[sellToken][buyToken][auctionIndex][user],
returned
);
} else {
// Auction has closed
// We DON'T want to check for returned > 0, because that would fail if a user claims
// intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens)
// Assign extra sell tokens (this is possible only after auction has cleared,
// because buyVolume could still increase before that)
uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex];
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// closingPrices.num represents buyVolume
// < 10^30 * 10^30 = 10^60
uint tokensExtra = mul(
buyerBalance,
extraTokensTotal
) / closingPrices[sellToken][buyToken][auctionIndex].num;
returned = add(returned, tokensExtra);
frtsIssued = issueFrts(
buyToken,
sellToken,
mul(buyerBalance, den) / num,
auctionIndex,
buyerBalance,
user
);
// Auction has closed
// Reset buyerBalances and claimedAmounts
buyerBalances[sellToken][buyToken][auctionIndex][user] = 0;
claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0;
}
// Claim tokens
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
balances[sellToken][user] = add(balances[sellToken][user], returned);
}
emit NewBuyerFundsClaim(
sellToken,
buyToken,
user,
auctionIndex,
returned,
frtsIssued
);
}
/// @dev allows to close possible theoretical closed markets
/// @param sellToken sellToken of an auction
/// @param buyToken buyToken of an auction
/// @param auctionIndex is the auctionIndex of the auction
function closeTheoreticalClosedAuction(address sellToken, address buyToken, uint auctionIndex) public {
if (auctionIndex == getAuctionIndex(
buyToken,
sellToken
) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) {
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
postBuyOrder(sellToken, buyToken, auctionIndex, 0);
}
}
}
}
/// @dev Claim buyer funds for one auction
function getUnclaimedBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
view
returns (
// < (10^67, 10^37)
uint unclaimedBuyerFunds,
uint num,
uint den
)
{
// R1: checks if particular auction has ever run
require(auctionIndex <= getAuctionIndex(sellToken, buyToken));
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
// This should rarely happen - as long as there is >= 1 buy order,
// auction will clear before price = 0. So this is just fail-safe
unclaimedBuyerFunds = 0;
} else {
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// < 10^30 * 10^37 = 10^67
unclaimedBuyerFunds = atleastZero(
int(mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user])
);
}
}
function getFeeRatio(address user)
public
view
returns (
// feeRatio < 10^4
uint num,
uint den
)
{
uint totalSupply = frtToken.totalSupply();
uint lockedFrt = frtToken.lockedTokenBalances(user);
/*
Fee Model:
locked FRT range Fee
----------------- ------
[0, 0.01%) 0.5%
[0.01%, 0.1%) 0.4%
[0.1%, 1%) 0.3%
[1%, 10%) 0.2%
[10%, 100%) 0.1%
*/
if (lockedFrt * 10000 < totalSupply || totalSupply == 0) {
// Maximum fee, if user has locked less than 0.01% of the total FRT
// Fee: 0.5%
num = 1;
den = 200;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 0.01% and less than 0.1% of the total FRT
// Fee: 0.4%
num = 1;
den = 250;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 0.1% and less than 1% of the total FRT
// Fee: 0.3%
num = 3;
den = 1000;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 1% and less than 10% of the total FRT
// Fee: 0.2%
num = 1;
den = 500;
} else {
// If user has locked more than 10% of the total FRT
// Fee: 0.1%
num = 1;
den = 1000;
}
}
//@ dev returns price in units [token2]/[token1]
//@ param token1 first token for price calculation
//@ param token2 second token for price calculation
//@ param auctionIndex index for the auction to get the averaged price from
function getPriceInPastAuction(
address token1,
address token2,
uint auctionIndex
)
public
view
// price < 10^31
returns (uint num, uint den)
{
if (block.coinbase == token2) { //injected CONTRACT AFFECTED BY MINERS
// C1
num = 1;
den = 1;
} else {
// C2
// R2.1
// require(auctionIndex >= 0);
// C3
// R3.1
require(auctionIndex <= getAuctionIndex(token1, token2));
// auction still running
uint i = 0;
bool correctPair = false;
Fraction memory closingPriceToken1;
Fraction memory closingPriceToken2;
while (!correctPair) {
closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i];
closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i];
if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 ||
closingPriceToken2.num > 0 && closingPriceToken2.den > 0)
{
correctPair = true;
}
i++;
}
// At this point at least one closing price is strictly positive
// If only one is positive, we want to output that
if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) {
num = closingPriceToken2.den;
den = closingPriceToken2.num;
} else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) {
num = closingPriceToken1.num;
den = closingPriceToken1.den;
} else {
// If both prices are positive, output weighted average
num = closingPriceToken2.den + closingPriceToken1.num;
den = closingPriceToken2.num + closingPriceToken1.den;
}
}
}
function scheduleNextAuction(
address sellToken,
address buyToken
)
internal
{
(uint sellVolume, uint sellVolumeOpp) = getSellVolumesInUSD(sellToken, buyToken);
bool enoughSellVolume = sellVolume >= thresholdNewAuction;
bool enoughSellVolumeOpp = sellVolumeOpp >= thresholdNewAuction;
bool schedule;
// Make sure both sides have liquidity in order to start the auction
if (enoughSellVolume && enoughSellVolumeOpp) {
schedule = true;
} else if (enoughSellVolume || enoughSellVolumeOpp) {
// But if the auction didn't start in 24h, then is enough to have
// liquidity in one of the two sides
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
uint clearingTime = getClearingTime(sellToken, buyToken, latestAuctionIndex - 1);
schedule = clearingTime <= now - 24 hours;
}
if (schedule) {
// Schedule next auction
setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION);
} else {
resetAuctionStart(sellToken, buyToken);
}
}
function getSellVolumesInUSD(
address sellToken,
address buyToken
)
internal
view
returns (uint sellVolume, uint sellVolumeOpp)
{
// Check if auctions received enough sell orders
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
uint sellNum;
uint sellDen;
(sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken);
uint buyNum;
uint buyDen;
(buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken);
// We use current sell volume, because in clearAuction() we set
// sellVolumesCurrent = sellVolumesNext before calling this function
// (this is so that we don't need case work,
// since it might also be called from postSellOrder())
// < 10^30 * 10^31 * 10^6 = 10^67
sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen;
sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen;
}
/// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network
/// @param token address of ERC-20 token
/// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume
function getPriceOfTokenInLastAuction(address token)
public
view
returns (
// price < 10^31
uint num,
uint den
)
{
uint latestAuctionIndex = getAuctionIndex(token, ethToken);
// getPriceInPastAuction < 10^30
(num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1);
}
function getCurrentAuctionPrice(address sellToken, address buyToken, uint auctionIndex)
public
view
returns (
// price < 10^37
uint num,
uint den
)
{
Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS
// Auction has closed
(num, den) = (closingPrice.num, closingPrice.den);
} else if (block.number > getAuctionIndex(sellToken, buyToken)) { //injected CONTRACT AFFECTED BY MINERS
(num, den) = (0, 0);
} else {
// Auction is running
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1);
// If we're calling the function into an unstarted auction,
// it will return the starting price of that auction
uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken)));
// The numbers below are chosen such that
// P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0
// 10^5 * 10^31 = 10^36
num = atleastZero(int((24 hours - timeElapsed) * pastNum));
// 10^6 * 10^31 = 10^37
den = mul((timeElapsed + 12 hours), pastDen);
if (block.gaslimit <= mul(den, buyVolumes[sellToken][buyToken])) { //injected CONTRACT AFFECTED BY MINERS
num = buyVolumes[sellToken][buyToken];
den = sellVolumesCurrent[sellToken][buyToken];
}
}
}
// > Helper fns
function getTokenOrder(address token1, address token2) public pure returns (address, address) {
if (token2 < token1) {
(token1, token2) = (token2, token1);
}
return (token1, token2);
}
function getAuctionStart(address token1, address token2) public view returns (uint auctionStart) {
(token1, token2) = getTokenOrder(token1, token2);
auctionStart = auctionStarts[token1][token2];
}
function getAuctionIndex(address token1, address token2) public view returns (uint auctionIndex) {
(token1, token2) = getTokenOrder(token1, token2);
auctionIndex = latestAuctionIndices[token1][token2];
}
function calculateFundedValueTokenToken(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
address ethTokenMem,
uint ethUSDPrice
)
internal
view
returns (uint fundedValueUSD)
{
// We require there to exist ethToken-Token auctions
// R3.1
require(getAuctionIndex(token1, ethTokenMem) > 0);
// R3.2
require(getAuctionIndex(token2, ethTokenMem) > 0);
// Price of Token 1
uint priceToken1Num;
uint priceToken1Den;
(priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1);
// Price of Token 2
uint priceToken2Num;
uint priceToken2Den;
(priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2);
// Compute funded value in ethToken and USD
// 10^30 * 10^30 = 10^60
uint fundedValueETH = add(
mul(token1Funding, priceToken1Num) / priceToken1Den,
token2Funding * priceToken2Num / priceToken2Den
);
fundedValueUSD = mul(fundedValueETH, ethUSDPrice);
}
function addTokenPairSecondPart(
address token1,
address token2,
uint token1Funding,
uint token2Funding
)
internal
{
balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding);
balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding);
// Fee mechanism, fees are added to extraTokens
uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding);
uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding);
// Update other variables
sellVolumesCurrent[token1][token2] = token1FundingAfterFee;
sellVolumesCurrent[token2][token1] = token2FundingAfterFee;
sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee;
sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee;
// Save clearingTime as adding time
(address tokenA, address tokenB) = getTokenOrder(token1, token2);
clearingTimes[tokenA][tokenB][0] = now;
setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR);
emit NewTokenPair(token1, token2);
}
function setClearingTime(
address token1,
address token2,
uint auctionIndex,
uint auctionStart,
uint sellVolume,
uint buyVolume
)
internal
{
(uint pastNum, uint pastDen) = getPriceInPastAuction(token1, token2, auctionIndex - 1);
// timeElapsed = (12 hours)*(2 * pastNum * sellVolume - buyVolume * pastDen)/
// (sellVolume * pastNum + buyVolume * pastDen)
uint numerator = sub(mul(mul(pastNum, sellVolume), 24 hours), mul(mul(buyVolume, pastDen), 12 hours));
uint timeElapsed = numerator / (add(mul(sellVolume, pastNum), mul(buyVolume, pastDen)));
uint clearingTime = auctionStart + timeElapsed;
(token1, token2) = getTokenOrder(token1, token2);
clearingTimes[token1][token2][auctionIndex] = clearingTime;
}
function getClearingTime(
address token1,
address token2,
uint auctionIndex
)
public
view
returns (uint time)
{
(token1, token2) = getTokenOrder(token1, token2);
time = clearingTimes[token1][token2][auctionIndex];
}
function issueFrts(
address primaryToken,
address secondaryToken,
uint x,
uint auctionIndex,
uint bal,
address user
)
internal
returns (uint frtsIssued)
{
if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) {
address ethTokenMem = ethToken;
// Get frts issued based on ETH price of returned tokens
if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
frtsIssued = bal;
} else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// 10^30 * 10^39 = 10^66
frtsIssued = x;
} else {
// Neither token is ethToken, so we use getHhistoricalPriceOracle()
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1);
// 10^30 * 10^35 = 10^65
frtsIssued = mul(bal, pastNum) / pastDen;
}
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
// Issue frtToken
frtToken.mintTokens(user, frtsIssued);
}
}
}
function settleFee(address primaryToken, address secondaryToken, uint auctionIndex, uint amount)
internal
returns (
// < 10^30
uint amountAfterFee
)
{
uint feeNum;
uint feeDen;
(feeNum, feeDen) = getFeeRatio(msg.sender);
// 10^30 * 10^3 / 10^4 = 10^29
uint fee = mul(amount, feeNum) / feeDen;
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
fee = settleFeeSecondPart(primaryToken, fee);
uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1];
extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee);
emit Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee);
}
amountAfterFee = sub(amount, fee);
}
function settleFeeSecondPart(address primaryToken, uint fee) internal returns (uint newFee) {
// Allow user to reduce up to half of the fee with owlToken
uint num;
uint den;
(num, den) = getPriceOfTokenInLastAuction(primaryToken);
// Convert fee to ETH, then USD
// 10^29 * 10^30 / 10^30 = 10^29
uint feeInETH = mul(fee, num) / den;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// 10^29 * 10^6 = 10^35
// Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD
uint feeInUSD = mul(feeInETH, ethUSDPrice);
uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, address(this)), feeInUSD / 2);
amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
owlToken.burnOWL(msg.sender, amountOfowlTokenBurned);
// Adjust fee
// 10^35 * 10^29 = 10^64
uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD;
newFee = sub(fee, adjustment);
} else {
newFee = fee;
}
}
// addClearTimes
/// @dev clears an Auction
/// @param sellToken sellToken of the auction
/// @param buyToken buyToken of the auction
/// @param auctionIndex of the auction to be cleared.
function clearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint sellVolume
)
internal
{
// Get variables
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken];
uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den;
uint auctionStart = getAuctionStart(sellToken, buyToken);
// Update closing price
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
closingPrices[sellToken][buyToken][auctionIndex] = Fraction(buyVolume, sellVolume);
}
// if (opposite is 0 auction OR price = 0 OR opposite auction cleared)
// price = 0 happens if auction pair has been running for >= 24 hrs
if (sellVolumeOpp == 0 || now >= auctionStart + 24 hours || closingPriceOppDen > 0) {
// Close auction pair
uint buyVolumeOpp = buyVolumes[buyToken][sellToken];
if (closingPriceOppDen == 0 && sellVolumeOpp > 0) {
// Save opposite price
closingPrices[buyToken][sellToken][auctionIndex] = Fraction(buyVolumeOpp, sellVolumeOpp);
}
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken];
// Update state variables for both auctions
sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
sellVolumesNext[sellToken][buyToken] = 0;
}
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
buyVolumes[sellToken][buyToken] = 0;
}
sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
sellVolumesNext[buyToken][sellToken] = 0;
}
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
buyVolumes[buyToken][sellToken] = 0;
}
// Save clearing time
setClearingTime(sellToken, buyToken, auctionIndex, auctionStart, sellVolume, buyVolume);
// Increment auction index
setAuctionIndex(sellToken, buyToken);
// Check if next auction can be scheduled
scheduleNextAuction(sellToken, buyToken);
}
emit AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex);
}
function setAuctionStart(address token1, address token2, uint value) internal {
(token1, token2) = getTokenOrder(token1, token2);
uint auctionStart = now + value;
uint auctionIndex = latestAuctionIndices[token1][token2];
auctionStarts[token1][token2] = auctionStart;
emit AuctionStartScheduled(token1, token2, auctionIndex, auctionStart);
}
function resetAuctionStart(address token1, address token2) internal {
(token1, token2) = getTokenOrder(token1, token2);
if (block.gaslimit != AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING;
}
}
function setAuctionIndex(address token1, address token2) internal {
(token1, token2) = getTokenOrder(token1, token2);
latestAuctionIndices[token1][token2] += 1;
}
function checkLengthsForSeveralAuctionClaiming(
address[] memory auctionSellTokens,
address[] memory auctionBuyTokens,
uint[] memory auctionIndices
) internal pure returns (uint length)
{
length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
}
// > Events
event NewDeposit(address indexed token, uint amount);
event NewWithdrawal(address indexed token, uint amount);
event NewSellOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewBuyOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewSellerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewBuyerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewTokenPair(address indexed sellToken, address indexed buyToken);
event AuctionCleared(
address indexed sellToken,
address indexed buyToken,
uint sellVolume,
uint buyVolume,
uint indexed auctionIndex
);
event AuctionStartScheduled(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint auctionStart
);
event Fee(
address indexed primaryToken,
address indexed secondarToken,
address indexed user,
uint auctionIndex,
uint fee
);
}
// File: @gnosis.pm/util-contracts/contracts/EtherToken.sol
/// @title Token contract - Token exchanging Ether 1:1
/// @author Stefan George - <[email protected]>
contract EtherToken is GnosisStandardToken {
using GnosisMath for *;
/*
* Events
*/
event Deposit(address indexed sender, uint value);
event Withdrawal(address indexed receiver, uint value);
/*
* Constants
*/
string public constant name = "Ether Token";
string public constant symbol = "ETH";
uint8 public constant decimals = 18;
/*
* Public functions
*/
/// @dev Buys tokens with Ether, exchanging them 1:1
function deposit() public payable {
balances[msg.sender] = balances[msg.sender].add(msg.value);
totalTokens = totalTokens.add(msg.value);
emit Deposit(msg.sender, msg.value);
}
/// @dev Sells tokens in exchange for Ether, exchanging them 1:1
/// @param value Number of tokens to sell
function withdraw(uint value) public {
// Balance covers value
balances[msg.sender] = balances[msg.sender].sub(value);
totalTokens = totalTokens.sub(value);
msg.sender.transfer(value);
emit Withdrawal(msg.sender, value);
}
}
// File: contracts/KyberDxMarketMaker.sol
interface KyberNetworkProxy {
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
external
view
returns (uint expectedRate, uint slippageRate);
}
contract KyberDxMarketMaker is Withdrawable {
// This is the representation of ETH as an ERC20 Token for Kyber Network.
ERC20 constant internal KYBER_ETH_TOKEN = ERC20(
0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
);
// Declared in DutchExchange contract but not public.
uint public constant DX_AUCTION_START_WAITING_FOR_FUNDING = 1;
enum AuctionState {
WAITING_FOR_FUNDING,
WAITING_FOR_OPP_FUNDING,
WAITING_FOR_SCHEDULED_AUCTION,
AUCTION_IN_PROGRESS,
WAITING_FOR_OPP_TO_FINISH,
AUCTION_EXPIRED
}
// Exposing the enum values to external tools.
AuctionState constant public WAITING_FOR_FUNDING = AuctionState.WAITING_FOR_FUNDING;
AuctionState constant public WAITING_FOR_OPP_FUNDING = AuctionState.WAITING_FOR_OPP_FUNDING;
AuctionState constant public WAITING_FOR_SCHEDULED_AUCTION = AuctionState.WAITING_FOR_SCHEDULED_AUCTION;
AuctionState constant public AUCTION_IN_PROGRESS = AuctionState.AUCTION_IN_PROGRESS;
AuctionState constant public WAITING_FOR_OPP_TO_FINISH = AuctionState.WAITING_FOR_OPP_TO_FINISH;
AuctionState constant public AUCTION_EXPIRED = AuctionState.AUCTION_EXPIRED;
DutchExchange public dx;
EtherToken public weth;
KyberNetworkProxy public kyberNetworkProxy;
// Token => Token => auctionIndex
mapping (address => mapping (address => uint)) public lastParticipatedAuction;
constructor(
DutchExchange _dx,
KyberNetworkProxy _kyberNetworkProxy
) public {
require(
address(_dx) != address(0),
"DutchExchange address cannot be 0"
);
require(
address(_kyberNetworkProxy) != address(0),
"KyberNetworkProxy address cannot be 0"
);
dx = DutchExchange(_dx);
weth = EtherToken(dx.ethToken());
kyberNetworkProxy = KyberNetworkProxy(_kyberNetworkProxy);
}
event KyberNetworkProxyUpdated(
KyberNetworkProxy kyberNetworkProxy
);
function setKyberNetworkProxy(
KyberNetworkProxy _kyberNetworkProxy
)
public
onlyAdmin
returns (bool)
{
require(
address(_kyberNetworkProxy) != address(0),
"KyberNetworkProxy address cannot be 0"
);
kyberNetworkProxy = _kyberNetworkProxy;
emit KyberNetworkProxyUpdated(kyberNetworkProxy);
return true;
}
event AmountDepositedToDx(
address indexed token,
uint amount
);
function depositToDx(
address token,
uint amount
)
public
onlyOperator
returns (uint)
{
require(ERC20(token).approve(address(dx), amount), "Cannot approve deposit");
uint deposited = dx.deposit(token, amount);
emit AmountDepositedToDx(token, deposited);
return deposited;
}
event AmountWithdrawnFromDx(
address indexed token,
uint amount
);
function withdrawFromDx(
address token,
uint amount
)
public
onlyOperator
returns (uint)
{
uint withdrawn = dx.withdraw(token, amount);
emit AmountWithdrawnFromDx(token, withdrawn);
return withdrawn;
}
/**
Claims funds from a specific auction.
sellerFunds - the amount in token wei of *buyToken* that was returned.
buyerFunds - the amount in token wei of *sellToken* that was returned.
*/
function claimSpecificAuctionFunds(
address sellToken,
address buyToken,
uint auctionIndex
)
public
returns (uint sellerFunds, uint buyerFunds)
{
uint availableFunds;
availableFunds = dx.sellerBalances(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
(sellerFunds, ) = dx.claimSellerFunds(
sellToken,
buyToken,
address(this),
auctionIndex
);
}
availableFunds = dx.buyerBalances(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
(buyerFunds, ) = dx.claimBuyerFunds(
sellToken,
buyToken,
address(this),
auctionIndex
);
}
}
/**
Participates in the auction by taking the appropriate step according to
the auction state.
Returns true if there is a step to be taken in this auction at this
stage, false otherwise.
*/
// TODO: consider removing onlyOperator limitation
function step(
address sellToken,
address buyToken
)
public
onlyOperator
returns (bool)
{
// KyberNetworkProxy.getExpectedRate() always returns a rate between
// tokens (and not between token wei as DutchX does).
// For this reason the rate is currently compatible only for tokens that
// have 18 decimals and is handled as though it is rate / 10**18.
// TODO: handle tokens with number of decimals other than 18.
require(
ERC20(sellToken).decimals() == 18 && ERC20(buyToken).decimals() == 18,
"Only 18 decimals tokens are supported"
);
// Deposit dxmm token balance to DutchX.
depositAllBalance(sellToken);
depositAllBalance(buyToken);
AuctionState state = getAuctionState(sellToken, buyToken);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
emit CurrentAuctionState(sellToken, buyToken, auctionIndex, state);
if (state == AuctionState.WAITING_FOR_FUNDING) {
// Update the dutchX balance with the funds from the previous auction.
claimSpecificAuctionFunds(
sellToken,
buyToken,
lastParticipatedAuction[sellToken][buyToken]
);
require(fundAuctionDirection(sellToken, buyToken));
return true;
}
if (state == AuctionState.WAITING_FOR_OPP_FUNDING ||
state == AuctionState.WAITING_FOR_SCHEDULED_AUCTION) {
return false;
}
if (state == AuctionState.AUCTION_IN_PROGRESS) {
if (isPriceRightForBuying(sellToken, buyToken, auctionIndex)) {
return buyInAuction(sellToken, buyToken);
}
return false;
}
if (state == AuctionState.WAITING_FOR_OPP_TO_FINISH) {
return false;
}
if (state == AuctionState.AUCTION_EXPIRED) {
dx.closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
dx.closeTheoreticalClosedAuction(buyToken, sellToken, auctionIndex);
return true;
}
// Should be unreachable.
revert("Unknown auction state");
}
function willAmountClearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
view
returns (bool)
{
uint buyVolume = dx.buyVolumes(sellToken, buyToken);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint num;
uint den;
(num, den) = dx.getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(div(mul(sellVolume, num), sub(den, buyVolume))));
return amount >= outstandingVolume;
}
// TODO: consider adding a "safety margin" to compensate for accuracy issues.
function thresholdNewAuctionToken(
address token
)
public
view
returns (uint)
{
uint priceTokenNum;
uint priceTokenDen;
(priceTokenNum, priceTokenDen) = dx.getPriceOfTokenInLastAuction(token);
// TODO: maybe not add 1 if token is WETH
// Rounding up to make sure we pass the threshold
return 1 + div(
// mul() takes care of overflows
mul(
dx.thresholdNewAuction(),
priceTokenDen
),
mul(
dx.ethUSDOracle().getUSDETHPrice(),
priceTokenNum
)
);
}
function calculateMissingTokenForAuctionStart(
address sellToken,
address buyToken
)
public
view
returns (uint)
{
uint currentAuctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint thresholdTokenWei = thresholdNewAuctionToken(sellToken);
if (block.timestamp > currentAuctionSellVolume) { //injected CONTRACT AFFECTED BY MINERS
return sub(thresholdTokenWei, currentAuctionSellVolume);
}
return 0;
}
function addFee(
uint amount
)
public
view
returns (uint)
{
uint num;
uint den;
(num, den) = dx.getFeeRatio(msg.sender);
// amount / (1 - num / den)
return div(
mul(amount, den),
sub(den, num)
);
}
function getAuctionState(
address sellToken,
address buyToken
)
public
view
returns (AuctionState)
{
// Unfunded auctions have an auctionStart time equal to a constant (1)
uint auctionStart = dx.getAuctionStart(sellToken, buyToken);
if (block.gaslimit == DX_AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
// Other side might also be not fully funded, but we're primarily
// interested in this direction.
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.WAITING_FOR_FUNDING;
} else {
return AuctionState.WAITING_FOR_OPP_FUNDING;
}
}
// DutchExchange logic uses auction start time.
/* solhint-disable-next-line not-rely-on-time */
if (block.number > now) { //injected CONTRACT AFFECTED BY MINERS
// After 24 hours have passed since last auction closed,
// DutchExchange will trigger a new auction even if only the
// opposite side is funded.
// In these cases we want this side to be funded as well.
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.WAITING_FOR_FUNDING;
} else {
return AuctionState.WAITING_FOR_SCHEDULED_AUCTION;
}
}
// If over 24 hours have passed, the auction is no longer viable and
// should be closed.
/* solhint-disable-next-line not-rely-on-time */
if (block.number > 24 hours) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.AUCTION_EXPIRED;
}
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
uint closingPriceDen;
(, closingPriceDen) = dx.closingPrices(sellToken, buyToken, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.AUCTION_IN_PROGRESS;
}
return AuctionState.WAITING_FOR_OPP_TO_FINISH;
}
function getKyberRate(
address _sellToken,
address _buyToken,
uint amount
)
public
view
returns (uint num, uint den)
{
// KyberNetworkProxy.getExpectedRate() always returns a rate between
// tokens (and not between token wei as DutchX does.
// For this reason the rate is currently compatible only for tokens that
// have 18 decimals and is handled as though it is rate / 10**18.
// TODO: handle tokens with number of decimals other than 18.
require(
ERC20(_sellToken).decimals() == 18 && ERC20(_buyToken).decimals() == 18,
"Only 18 decimals tokens are supported"
);
// Kyber uses a special constant address for representing ETH.
ERC20 sellToken = _sellToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_sellToken);
ERC20 buyToken = _buyToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_buyToken);
uint rate;
(rate, ) = kyberNetworkProxy.getExpectedRate(
sellToken,
buyToken,
amount
);
return (rate, 10 ** 18);
}
function tokensSoldInCurrentAuction(
address sellToken,
address buyToken,
uint auctionIndex,
address account
)
public
view
returns (uint)
{
return dx.sellerBalances(sellToken, buyToken, auctionIndex, account);
}
// The amount of tokens that matches the amount sold by provided account in
// specified auction index, deducting the amount that was already bought.
function calculateAuctionBuyTokens(
address sellToken,
address buyToken,
uint auctionIndex,
address account
)
public
view
returns (uint)
{
uint sellVolume = tokensSoldInCurrentAuction(
sellToken,
buyToken,
auctionIndex,
account
);
uint num;
uint den;
(num, den) = dx.getCurrentAuctionPrice(
sellToken,
buyToken,
auctionIndex
);
// No price for this auction, it is a future one.
if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS
uint wantedBuyVolume = div(mul(sellVolume, num), den);
uint auctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint buyVolume = dx.buyVolumes(sellToken, buyToken);
uint outstandingBuyVolume = atleastZero(
int(mul(auctionSellVolume, num) / den - buyVolume)
);
return wantedBuyVolume < outstandingBuyVolume
? wantedBuyVolume
: outstandingBuyVolume;
}
function atleastZero(int a)
public
pure
returns (uint)
{
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
event AuctionDirectionFunded(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint sellTokenAmount,
uint sellTokenAmountWithFee
);
function fundAuctionDirection(
address sellToken,
address buyToken
)
internal
returns (bool)
{
uint missingTokens = calculateMissingTokenForAuctionStart(
sellToken,
buyToken
);
uint missingTokensWithFee = addFee(missingTokens);
if (block.timestamp == 0) return false; //injected CONTRACT AFFECTED BY MINERS
uint balance = dx.balances(sellToken, address(this));
require(
balance >= missingTokensWithFee,
"Not enough tokens to fund auction direction"
);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
dx.postSellOrder(sellToken, buyToken, auctionIndex, missingTokensWithFee);
lastParticipatedAuction[sellToken][buyToken] = auctionIndex;
emit AuctionDirectionFunded(
sellToken,
buyToken,
auctionIndex,
missingTokens,
missingTokensWithFee
);
return true;
}
// TODO: check for all the requirements of dutchx
event BoughtInAuction(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
uint buyTokenAmount,
bool clearedAuction
);
/**
Will calculate the amount that the bot has sold in current auction and
buy that amount.
Returns false if ended up not buying.
Reverts if no auction active or not enough tokens for buying.
*/
function buyInAuction(
address sellToken,
address buyToken
)
internal
returns (bool bought)
{
require(
getAuctionState(sellToken, buyToken) == AuctionState.AUCTION_IN_PROGRESS,
"No auction in progress"
);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
uint buyTokenAmount = calculateAuctionBuyTokens(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return false;
}
bool willClearAuction = willAmountClearAuction(
sellToken,
buyToken,
auctionIndex,
buyTokenAmount
);
if (!willClearAuction) {
buyTokenAmount = addFee(buyTokenAmount);
}
require(
dx.balances(buyToken, address(this)) >= buyTokenAmount,
"Not enough buy token to buy required amount"
);
dx.postBuyOrder(sellToken, buyToken, auctionIndex, buyTokenAmount);
emit BoughtInAuction(
sellToken,
buyToken,
auctionIndex,
buyTokenAmount,
willClearAuction
);
return true;
}
function depositAllBalance(
address token
)
internal
returns (uint)
{
uint amount;
uint balance = ERC20(token).balanceOf(address(this));
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
amount = depositToDx(token, balance);
}
return amount;
}
event CurrentAuctionState(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
AuctionState auctionState
);
event PriceIsRightForBuying(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
uint amount,
uint dutchExchangePriceNum,
uint dutchExchangePriceDen,
uint kyberPriceNum,
uint kyberPriceDen
);
function isPriceRightForBuying(
address sellToken,
address buyToken,
uint auctionIndex
)
internal
returns (bool)
{
uint amount = calculateAuctionBuyTokens(
sellToken,
buyToken,
auctionIndex,
address(this)
);
uint dNum;
uint dDen;
(dNum, dDen) = dx.getCurrentAuctionPrice(
sellToken,
buyToken,
auctionIndex
);
uint kNum;
uint kDen;
(kNum, kDen) = getKyberRate(sellToken, buyToken, amount);
// TODO: Check for overflow explicitly?
bool shouldBuy = mul(dNum, kDen) <= mul(kNum, dDen);
// TODO: should we add a boolean for shouldBuy?
emit PriceIsRightForBuying(
sellToken,
buyToken,
auctionIndex,
amount,
dNum,
dDen,
kNum,
kDen
);
return shouldBuy;
}
// --- Safe Math functions ---
// (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol)
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero,
// but the benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on
division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if
subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
} | Allows the current admin to set the pendingAdmin address. newAdmin The address to transfer ownership to./ | function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin address cannot be 0");
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
| 5,418,260 |
pragma solidity >0.4.99 <0.6.0;
import "./CAT20Protected.sol";
import "./CAT20Transfer.sol";
import "../../../interfaces/ITxCheckpoints.sol";
import "../../../../../common/libraries/SafeMath.sol";
/**
* @title CAT-20 Rollback
*/
contract CAT20Rollback is CAT20Protected, CAT20Transfer {
// Define libraries
using SafeMath for uint;
// Write info to the log about rollbacks status changes
event RollbacksStatusChanged(bool newStatus);
// Write info to the log when the checkpoint was used
event CheckpointWasUsed(uint indexed checkpointId, string originalTxHash);
/**
* @notice Describe event of the "rollback transaction" and write info to the log
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
* @param checkpointId Checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
event RollbackTransaction(
address from,
address to,
uint tokens,
uint checkpointId,
string originalTxHash
);
/**
* @notice Allows create rollback transaction for ERC-20 tokens
* @notice tokens will be send back to the old owner, will be emited "RollbackTransaction" event
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param sender Original transaction sender
* @param tokens Quantity of the tokens that will be rollbacked
* @param checkpointId Transaction checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
function createRollbackTransaction(
address from,
address to,
address sender,
uint tokens,
uint checkpointId,
string memory originalTxHash
)
public
verifyPermission(msg.sig, msg.sender)
returns (bool)
{
processCheckpoint(
from,
to,
tokens,
sender,
checkpointId,
originalTxHash
);
emit RollbackTransaction(
from,
to,
tokens,
checkpointId,
originalTxHash
);
return _transfer(from, to, tokens);
}
/**
* @notice Enable/Disable rollbacks in the token
*/
function toggleRollbacksStatus()
external
verifyPermission(msg.sig, msg.sender)
{
rollbackEnabled = !rollbackEnabled;
emit RollbacksStatusChanged(rollbackEnabled);
}
/**
* @notice Verify and deactivate transaction checkpoin
* @param from Address from which we write off tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
* @param sender Transaction initiator
* @param checkpointId Transaction checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
function processCheckpoint(
address from,
address to,
uint tokens,
address sender,
uint checkpointId,
string memory originalTxHash
)
internal
{
bytes32 generatedCheckpointKey = ITxCheckpoints(address(this)).generateCheckpoint(
to,
from,
tokens,
sender
);
bytes32 checkpointKey = ITxCheckpoints(address(this)).getCheckpointKey(checkpointId);
require(generatedCheckpointKey == checkpointKey, "Invalid input parameters");
require(
ITxCheckpoints(address(this)).isActiveCheckpoint(checkpointId),
"Checkpoint is already used or expired"
);
deactivateCheckpoint(checkpointId, originalTxHash);
}
/**
* @notice Change checkpoint status to not active
* @param checkpointId Checkpoint identifier
* @param originalTxHash The hash of the transaction which was canceled or rollbacked
*/
function deactivateCheckpoint(uint checkpointId, string memory originalTxHash) internal {
require(checkpoints[checkpointId].expireDate != 0, "Invalid checkpoint.");
require(!checkpoints[checkpointId].used, "Checkpoint is already used.");
checkpoints[checkpointId].used = true;
emit CheckpointWasUsed(checkpointId, originalTxHash);
}
} | Enable/Disable rollbacks in the token/ | function toggleRollbacksStatus()
external
verifyPermission(msg.sig, msg.sender)
{
rollbackEnabled = !rollbackEnabled;
emit RollbacksStatusChanged(rollbackEnabled);
}
| 5,412,430 |
// SPDX-License-Identifier: MIT
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@ %%%%%%%%%%%% %%%%%%%%#*. @@@@
// @@@@ ,#%%%%%%%%&(%%%%%%%%%/ %%%%%. %%%%%%%%%%%%%%*/*%%%*# (%%%%.*.*#%%%#%%%%%%%%%% @@@@
// @@@@ %%%%%%%%%%%%* (%%,%%&%%%%%/ %%%%%%%(/ %%%%% *%%%%%%%%#% %%%%% %%%%%%%#%%.%/ @@@@
// @@@@ *%%%&# %%%%% %%%%% %%%%% %%%%&(%%%% %%%%&.%%&% %%%%%%%%%%%% %%%% @@@@
// @@@@ %%%%% .%%%%%%%%%%%%%,%%%%%% %%%%% %%% %%%%.*%%%%% %%%%% ,%#%%%%%%%%% @@@@
// @@@@ %%%%/* %%%%%%%%%%%%%, %%%%%%%%%%%%%%% %%%%%%%%%%,% %%%%% %%%%%%%%%&%/, %%%%, @@@@
// @@@@ %%%%& %%%%# %%%%% %%%%% %%%%* .,*. %%%%( ,(%%&%(*.*###&%%%%%%%%%.% @@@@
// @@@@ %%&#* /%/.. . #%%%%%%%( @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
pragma solidity 0.8.13;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
/**
* @title Tradies Founders Pass
* @author @jonathansnow
* @notice Tradies Founders Pass is an ERC721 token that provides access to the Tradies ecosystem.
*/
contract TradiesFoundersPass is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _nextTokenId;
string private _baseTokenURI;
uint256 public constant TEAM_SUPPLY = 20;
uint256 public constant MAX_SUPPLY = 400;
uint256 public constant MAX_MINT = 3;
uint256 public constant PRICE = 0.15 ether;
bool public saleIsActive;
bool public saleIsLocked;
mapping (address => uint256) public mintBalance;
address public a1 = 0xa238Db3aE883350DaDa3592345e8A0d318b06e82; // Treasury
address public constant a2 = 0xCAe379DD33Cc01D276E57b40924C20a8312197AA; // Dev
address public constant a3 = 0x46CeDbDf6D4E038293C66D9e0E999A5e97a5119C; // Team
constructor() ERC721("TradiesFoundersPass", "TDFP") {
_nextTokenId.increment(); // Start Token Ids at 1
}
/**
* @notice Public minting function for whitelisted addresses
* @dev Sale must be active, sale must not be locked, and minter must not mint more than 3 tokens..
* @param quantity the number of tokens to mint
*/
function mint(uint256 quantity) public payable {
require(saleIsActive, "Sale is not active yet.");
require(!saleIsLocked , "Sale is closed.");
require(quantity > 0, "Must mint more than 0.");
require(totalSupply() + quantity <= MAX_SUPPLY, "Exceeds max available.");
require(mintBalance[msg.sender] + quantity <= MAX_MINT, "No mints remaining.");
require(msg.value == quantity * PRICE, "Wrong ETH value sent.");
mintBalance[msg.sender] += quantity;
for (uint256 i = 0; i < quantity; i++) {
_safeMint(msg.sender, _nextTokenId.current());
_nextTokenId.increment();
}
}
/**
* @notice Get the number of passes minted
* @return uint256 number of passes minted
*/
function totalSupply() public view returns (uint256) {
return _nextTokenId.current() - 1;
}
/**
* @notice Get baseURI
* @dev Overrides default ERC721 _baseURI()
* @return baseURI the base token URI for the collection
*/
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/**
* @notice Update the baseURI
* @dev URI must include trailing slash
* @param baseURI the new metadata URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
/**
* @notice Toggle public sale on/off
*/
function toggleSale() external onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @notice Permanently disable the public sale
* @dev This is a supply shrink mechanism in the event we want to permanently prevent further minting.
*/
function disableSale() external onlyOwner {
saleIsLocked = true;
}
/**
* @notice Admin minting function
* @dev Allows the team to mint up to 20 tokens. The tokens must be minted prior to public sale.
* @param quantity the number of tokens to mint
* @param recipient the address to mint the tokens to
*/
function adminMint(uint256 quantity, address recipient) public onlyOwner {
require(totalSupply() + quantity <= TEAM_SUPPLY, "Exceeds max team amount.");
for (uint256 i = 0; i < quantity; i++) {
_safeMint(recipient, _nextTokenId.current());
_nextTokenId.increment();
}
}
/**
* @notice Update the Treasury address
* @dev Allows the team to update the address they will use to receive Treasury funds.
*/
function updateTreasury(address newAddress) external onlyOwner {
a1 = newAddress;
}
/**
* @notice Function to withdraw funds from the contract with splits
* @dev Transfers 92% of the contract ETH balance to the Treasury address, 5% to dev partner, and 3% to the
* mod Gnosis wallet. Any balance remaining after the split transfers will be sent to the Treasury.
*/
function withdrawBalance() external onlyOwner {
uint256 balance = address(this).balance;
_withdraw(a1, (balance * 92) / 100 ); // 92%
_withdraw(a2, (balance * 5) / 100 ); // 5%
_withdraw(a3, (balance * 3) / 100 ); // 3%
_withdraw(a1, address(this).balance ); // Remainder
}
/**
* @notice Function to send ETH to a specific address
* @dev Using call to ensure that transfer will succeed for both EOA and Gnosis Addresses.
*/
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = payable(_address).call{ value: _amount }("");
require(success, "Transfer failed");
}
}
// 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;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Update the Treasury address Allows the team to update the address they will use to receive Treasury funds./ | function updateTreasury(address newAddress) external onlyOwner {
a1 = newAddress;
}
| 11,723,141 |
./full_match/44787/0xFe8e232B18fb6E6D3246D4eC13676D932962847e/sources/project_/contracts/CASRegistryManager.sol | assign tokens from the project to the holder projectInput ( projectAddress: bytes(address), bundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string) projectAddress: bytes(address) ) holderOutput ( holderAddress: bytes(address), outputBundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string) projectAddress: bytes(address) ) All parameters must be passed in bytes and opened in the contract as the required type/ | function assignTokens(bytes[] memory projectInput, bytes[] memory holderOutput) external checkAccess {
require(
keccak256(abi.encodePacked(projectInput[3])) == keccak256(abi.encodePacked(holderOutput[3])),
"same types must be assigned at projectInput, holderOutput"
);
require(
BytesLib.toUint256(projectInput[2], 0) == BytesLib.toUint256(holderOutput[2], 0),
"same amount must be assigned at projectInput, holderOutput"
);
IProject(projectContractAddress).subtractBundleVolume(projectInput);
IHolder(holderContractAddress).addBundleVolume(holderOutput);
}
| 13,287,488 |
// SPDX-License-Identifier: MIT
/* OpenZeppelin Standard Imports */
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
pragma solidity 0.8.10;
/* Interface for Pancakeswap V2 Factory */
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
/* Interface for Pancakeswap v2 pair */
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event 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 burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/* Interface for Pancakeswap route V1 */
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
/* Interface for Pancakeswap Route V2 */
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/* Main Contract of Worthpad Token starts here */
contract WorthToken is Context, IERC20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
string private constant NAME = "Worthpad";
string private constant SYMBOL = "WORTH";
uint8 private constant DECIMALS = 18;
uint256 private constant FEES_DIVISOR = 10**3;
uint256 private constant TOTAL_SUPPLY = 100 * 10**9 * 10**DECIMALS;
uint256 public _liquidityFee = 25;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _worthDVCFundFee = 25;
address public worthDVCFundWallet;
uint256 private _previousWorthDVCFundFee = _worthDVCFundFee;
uint256 private withdrawableBalance;
uint256 public _maxTxAmount = 10 * 10**6 * 10**DECIMALS;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 private numTokensSellToAddToLiquidity = 1 * 10**6 * 10**DECIMALS;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event ExcludeFromFeeEvent(bool value);
event IncludeInFeeEvent(bool value);
event SetWorthDVCFundWalletEvent(address value);
event SetLiquidityFeePercentEvent(uint256 value);
event SetWorthDVCFundFeePercentEvent(uint256 value);
event SetNumTokensSellToAddToLiquidityEvent(uint256 value);
event SetMaxTxAmountEvent(uint256 value);
event SetRouterAddressEvent(address value);
event BNBWithdrawn(address beneficiary,uint256 value);
constructor (address _worthDVCFundWallet) {
require(_worthDVCFundWallet != address(0),"Should not be address 0");
_balances[_msgSender()] = TOTAL_SUPPLY;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
/* Create a Pancakeswap pair for this new token */
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
/* Set the rest of the contract variables */
uniswapV2Router = _uniswapV2Router;
/* Exclude owner and this contract from fee */
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
worthDVCFundWallet = _worthDVCFundWallet;
emit Transfer(address(0), _msgSender(), TOTAL_SUPPLY);
}
/* Function : Returns Name of token */
/* Parameter : -- */
/* Public View function */
function name() public pure returns (string memory) {
return NAME;
}
/* Function : Returns Symbol of token */
/* Parameter : -- */
/* Public Pure function */
function symbol() public pure returns (string memory) {
return SYMBOL;
}
/* Function : Returns Decimal of token */
/* Parameter : -- */
/* Public Pure function */
function decimals() public pure returns (uint8) {
return DECIMALS;
}
/* Function : Returns total supply of token */
/* Parameter : -- */
/* Public Pure function */
function totalSupply() public pure override returns (uint256) {
return TOTAL_SUPPLY;
}
/* Function : Function to check balance of the address */
/* Parameter : Wallet/Contract Address */
/* Public View function */
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/* Function : Function to check the value of Min Auto Liquidity Sell Amount */
/* Parameters : -- */
/* Public View Function */
function getMinAutoLiquidityAmount() public view returns (uint256) {
return numTokensSellToAddToLiquidity;
}
/**
* @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) public override nonReentrant returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @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) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @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) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @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) public override nonReentrant returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/* Function : Function to Increase the approved allowance */
/* Parameter 1 : Spenders Address */
/* Parameter 2 : Value which needs to be added */
/* Public function */
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/* Function : Function to Decrease the approved allowance */
/* Parameter 1 : Spenders Address */
/* Parameter 2 : Value which needs to be deducted */
/* Public function */
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;
}
/* To receive BNB from uniswapV2Router when swapping */
receive() external payable {}
/* Function : Checks if a address is excluded from fee or not */
/* Parameters : Address of the wallet/contract */
/* Public View Function */
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
/* Internal Approve function to approve a token for trade/contract interaction */
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/* Internal Transfer function of Token */
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
/*
- Is the token balance of this contract address over the min number of
- Tokens that we need to initiate a swap + liquidity lock?
- Also, don't get caught in a circular liquidity event.
- Also, don't swap & liquify if sender is Pancakeswap pair.
*/
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
/* Add liquidity */
swapAndLiquify(contractTokenBalance);
}
/* Transfer amount, it will take Worth DVC Fund Fee and Liquidity Fee */
_tokenTransfer(from,to,amount);
}
/* Internal Function to swap Tokens and add to Liquidity */
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
/* Split the contract balance into halves */
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
/*
- Capture the contract's current BNB balance.
- This is so that we can capture exactly the amount of BNB that the
- Swap creates, and not make the liquidity event include any BNB that
- Has been manually sent to the contract
*/
uint256 initialBalance = address(this).balance;
/* Swap tokens for BNB */
swapTokensForEth(half); // <- This breaks the BNB -> WORTH swap when swap+liquify is triggered
/* How much BNB did we just swap into? */
uint256 newBalance = address(this).balance.sub(initialBalance);
/* Add liquidity to Pancakeswap */
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
/* Internal Function to swap tokens for BNB */
function swapTokensForEth(uint256 tokenAmount) private {
/* Generate the Pancakeswap pair path of token -> wbnb */
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
/* Make the swap */
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
/* Internal function to Add Liquidity */
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
/* Approve token transfer to cover all possible scenarios */
_approve(address(this), address(uniswapV2Router), tokenAmount);
/* Add the liquidity */
uniswapV2Router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
// fix the forever locked BNBs
/**
* The swapAndLiquify function converts half of the tokens to BNB.
* For every swapAndLiquify function call, a small amount of BNB remains in the contract.
* This amount grows over time with the swapAndLiquify function being called throughout the life
* of the contract.
*/
withdrawableBalance = address(this).balance;
}
/* Internal Basic function for Token Transfer */
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > FEES_DIVISOR.div(_worthDVCFundFee), "Transaction amount is too small");
require(amount > FEES_DIVISOR.div(_liquidityFee), "Transaction amount is too small");
uint256 worthDVCFundFee = 0;
uint256 liquidityAmount = 0;
if (_isExcludedFromFee[sender]) {
_transferStandard(sender, recipient, amount);
} else {
if(_worthDVCFundFee > 0) {
/* Calculate WorthDVCFund Fee */
worthDVCFundFee = amount.mul(_worthDVCFundFee).div(FEES_DIVISOR);
}
if(_liquidityFee > 0) {
/* Calculate Liquidity Fee */
liquidityAmount = amount.mul(_liquidityFee).div(FEES_DIVISOR);
}
_transferStandard(sender, recipient, (amount.sub(worthDVCFundFee).sub(liquidityAmount)));
_transferStandard(sender, worthDVCFundWallet, worthDVCFundFee);
_transferStandard(sender, address(this), liquidityAmount);
}
}
/* Internal Standard Transfer function for Token */
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
_balances[sender] = _balances[sender].sub(tAmount);
_balances[recipient] = _balances[recipient].add(tAmount);
emit Transfer(sender, recipient, tAmount);
}
/* Function : Exclude A wallet/contract in fee taking */
/* Parameters : Address of wallet/contract */
/* Only Owner Function */
function excludeFromFee(address account) external onlyOwner {
require(_isExcludedFromFee[account] == false, "Address is already excluded from Fee");
_isExcludedFromFee[account] = true;
emit ExcludeFromFeeEvent(true);
}
/* Function : Include A wallet/contract in fee taking */
/* Parameters : Address of wallet/contract */
/* Only Owner Function */
function includeInFee(address account) external onlyOwner {
require(_isExcludedFromFee[account] == true, "Address is already included in Fee");
_isExcludedFromFee[account] = false;
emit IncludeInFeeEvent(true);
}
/* Function : Disables the Liquidity and Worth DVC Fund fee */
/* Parameters : -- */
/* Only Owner Function */
function disableAllFees() external onlyOwner {
delete _liquidityFee;
_previousLiquidityFee = _liquidityFee;
delete _worthDVCFundFee;
_previousWorthDVCFundFee = _worthDVCFundFee;
swapAndLiquifyEnabled = false;
emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled);
}
/* Function : Enables The Liquidity and Worth DVC Fund fee */
/* Parameters : -- */
/* Only Owner Function */
function enableAllFees() external onlyOwner {
_liquidityFee = 25;
_previousLiquidityFee = _liquidityFee;
_worthDVCFundFee = 25;
_previousWorthDVCFundFee = _worthDVCFundFee;
swapAndLiquifyEnabled = true;
emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled);
}
/* Function : Set New Worth DVC Fund wallet */
/* Parameters : New Worth DVC Fund Wallet address */
/* Only Owner Function */
function setWorthDVCFundWallet(address newWallet) external onlyOwner {
require(newWallet != address(0),"Should not be address 0");
require(newWallet != worthDVCFundWallet,"Should be a new Address");
worthDVCFundWallet = newWallet;
emit SetWorthDVCFundWalletEvent(newWallet);
}
/* Function : Set Liquidity fee percentage */
/* Parameters : New Percentage to be executed */
/* Only Owner Function */
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
require(liquidityFee >= 10 && liquidityFee <= 100, "Liquidity Fee can never be set below 1% or exceed 10%");
_liquidityFee = liquidityFee;
emit SetLiquidityFeePercentEvent(liquidityFee);
}
/* Function : Set Worth DVC Fund fee percentage */
/* Parameters : New Percentage to be executed */
/* Only Owner Function */
function setWorthDVCFundFeePercent(uint256 worthDVCFundFee) external onlyOwner {
require(worthDVCFundFee >= 10 && worthDVCFundFee <= 100, "Worth DVC Fund Fee can never be set below 1% or exceed 10%");
_worthDVCFundFee = worthDVCFundFee;
emit SetWorthDVCFundFeePercentEvent(worthDVCFundFee);
}
/* Function : Set Minimum amount for swapping to Liquify for Liquidity Addition */
/* Parameters : Enter the Minimum Token to swap */
/* Only Owner Function */
function setNumTokensSellToAddToLiquidity(uint256 amount) external onlyOwner {
require(amount > 0 && amount < _maxTxAmount, "Minimum Sell Amount should be greater than 0 and less than max transaction amount");
numTokensSellToAddToLiquidity = amount * 10**DECIMALS;
emit SetNumTokensSellToAddToLiquidityEvent(amount);
}
/* Function : Set Max transaction amount for each transfer */
/* Parameters : Max Amount of token to be swapped */
/* Only Owner Function */
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner {
require(maxTxAmount > 0 && maxTxAmount < 100000000, "Max Transaction Amount should be greater than 0 and less than 0.1% of the total supply");
_maxTxAmount = maxTxAmount * 10**DECIMALS;
emit SetMaxTxAmountEvent(maxTxAmount);
}
/* Function : Set a new router if released */
/* Parameters : New router Address */
/* Only Owner Function */
function setRouterAddress(address newRouter) external onlyOwner {
require(newRouter != address(0),"Should not be address 0");
IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(newRouter);
uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH());
uniswapV2Router = _newPancakeRouter;
emit SetRouterAddressEvent(newRouter);
}
/* Function : Turns ON/OFF Liquidity swap */
/* Parameters : Set 'true' to turn ON and 'false' to turn OFF */
/* Only Owner Function */
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled);
}
/**
* @dev The owner can withdraw BNB collected in the contract from `swapAndLiquify`
* or if someone (accidentally) sends BNB directly to the contract.
*
* The swapAndLiquify function converts half of the tokens to BNB.
* For every swapAndLiquify function call, a small amount of BNB remains in the contract.
* This amount grows over time with the swapAndLiquify function being called
* throughout the life of the contract.
*/
/* Only Owner Function */
function withdrawLockedBNB(address payable recipient) external onlyOwner {
require(recipient != address(0), "Cannot withdraw the BNB balance to the zero address");
require(withdrawableBalance > 0, "The BNB balance must be greater than 0");
// prevent re-entrancy attacks
uint256 amount = withdrawableBalance;
withdrawableBalance = 0;
(bool success, ) = recipient.call{value:amount}("");
require(success, "Transfer failed.");
emit BNBWithdrawn(recipient, amount);
}
}
| Function : Set Worth DVC Fund fee percentage / Parameters : New Percentage to be executed / Only Owner Function / | function setWorthDVCFundFeePercent(uint256 worthDVCFundFee) external onlyOwner {
require(worthDVCFundFee >= 10 && worthDVCFundFee <= 100, "Worth DVC Fund Fee can never be set below 1% or exceed 10%");
_worthDVCFundFee = worthDVCFundFee;
emit SetWorthDVCFundFeePercentEvent(worthDVCFundFee);
}
| 2,578,636 |
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./ERC1820Client.sol";
import "../interface/ERC1820Implementer.sol";
import "../extensions/userExtensions/IERC1400TokensRecipient.sol";
import "../ERC1400.sol";
/**
***************************************************************************************************************
**************************************** CAUTION: work in progress ********************************************
***************************************************************************************************************
*
* CAUTION: This contract is a work in progress, tests are not finalized yet!
*
***************************************************************************************************************
**************************************** CAUTION: work in progress ********************************************
***************************************************************************************************************
*/
/**
* @title FundIssuer
* @dev Fund issuance contract.
* @dev Intended usage:
* The purpose of the contract is to perform a fund issuance.
*
*/
contract FundIssuer is ERC1820Client, IERC1400TokensRecipient, ERC1820Implementer {
using SafeMath for uint256;
bytes32 constant internal ORDER_SUBSCRIPTION_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc;
bytes32 constant internal ORDER_PAYMENT_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd;
bytes32 constant internal BYPASS_ACTION_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
string constant internal FUND_ISSUER = "FundIssuer";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
enum CycleState {Undefined, Subscription, Valuation, Payment, Settlement, Finalized}
enum OrderState {Undefined, Subscribed, Paid, PaidSettled, UnpaidSettled, Cancelled, Rejected}
enum OrderType {Undefined, Value, Amount}
enum Payment {OffChain, ETH, ERC20, ERC1400}
enum AssetValue {Unknown, Known}
struct AssetRules {
bool defined;
uint256 firstStartTime;
uint256 subscriptionPeriodLength;
uint256 valuationPeriodLength;
uint256 paymentPeriodLength;
AssetValue assetValueType;
uint256 assetValue;
uint256 reverseAssetValue;
Payment paymentType;
address paymentAddress;
bytes32 paymentPartition;
address fundAddress;
bool subscriptionsOpened;
}
struct Cycle {
address assetAddress;
bytes32 assetClass;
uint256 startTime;
uint256 subscriptionPeriodLength;
uint256 valuationPeriodLength;
uint256 paymentPeriodLength;
AssetValue assetValueType;
uint256 assetValue;
uint256 reverseAssetValue;
Payment paymentType;
address paymentAddress;
bytes32 paymentPartition;
address fundAddress;
bool finalized;
}
struct Order {
uint256 cycleIndex;
address investor;
uint256 value;
uint256 amount;
OrderType orderType;
OrderState state;
}
// Mapping from (assetAddress, assetClass) to asset rules.
mapping(address => mapping(bytes32 => AssetRules)) internal _assetRules;
// Index of most recent cycle.
uint256 internal _cycleIndex;
// Mapping from cycle index to cycle.
mapping(uint256 => Cycle) internal _cycles;
// Mapping from (assetAddress, assetClass) to most recent cycle.
mapping(address => mapping (bytes32 => uint256)) internal _lastCycleIndex;
// Index of most recent order.
uint256 internal _orderIndex;
// Mapping from order index to order.
mapping(uint256 => Order) internal _orders;
// Mapping from cycle index to order list.
mapping(uint256 => uint256[]) internal _cycleOrders;
// Mapping from investor address to order list.
mapping(address => uint256[]) internal _investorOrders;
// Mapping from assetAddress to amount of escrowed ETH.
mapping(address => uint256) internal _escrowedEth;
// Mapping from (assetAddress, paymentAddress) to amount of escrowed ERC20.
mapping(address => mapping (address => uint256)) internal _escrowedErc20;
// Mapping from (assetAddress, paymentAddress, paymentPartition) to amount of escrowed ERC1400.
mapping(address => mapping (address => mapping (bytes32 => uint256))) internal _escrowedErc1400;
// Mapping from token to token controllers.
mapping(address => address[]) internal _tokenControllers;
// Mapping from (token, operator) to token controller status.
mapping(address => mapping(address => bool)) internal _isTokenController;
// Mapping from token to price oracles.
mapping(address => address[]) internal _priceOracles;
// Mapping from (token, operator) to price oracle status.
mapping(address => mapping(address => bool)) internal _isPriceOracle;
/**
* @dev Modifier to verify if sender is a token controller.
*/
modifier onlyTokenController(address tokenAddress) {
require(_tokenController(msg.sender, tokenAddress),
"Sender is not a token controller."
);
_;
}
/**
* @dev Modifier to verify if sender is a price oracle.
*/
modifier onlyPriceOracle(address assetAddress) {
require(_checkPriceOracle(assetAddress, msg.sender), "Sender is not a price oracle.");
_;
}
/**
* [DVP CONSTRUCTOR]
* @dev Initialize Fund issuance contract + register
* the contract implementation in ERC1820Registry.
*/
constructor() public {
ERC1820Implementer._setInterface(FUND_ISSUER);
ERC1820Implementer._setInterface(ERC1400_TOKENS_RECIPIENT);
setInterfaceImplementation(ERC1400_TOKENS_RECIPIENT, address(this));
}
/**
* [ERC1400TokensRecipient INTERFACE (1/2)]
* @dev Indicate whether or not the fund issuance contract can receive the tokens or not. [USED FOR ERC1400 TOKENS ONLY]
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the DVP transfer, by the operator.
* @return 'true' if the DVP contract can receive the tokens, 'false' if not.
*/
function canReceive(bytes calldata, bytes32, address, address, address, uint, bytes calldata data, bytes calldata operatorData) external override view returns(bool) {
return(_canReceive(data, operatorData));
}
/**
* [ERC1400TokensRecipient INTERFACE (2/2)]
* @dev Hook function executed when tokens are sent to the fund issuance contract. [USED FOR ERC1400 TOKENS ONLY]
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the DVP transfer, by the operator.
*/
function tokensReceived(bytes calldata, bytes32 partition, address, address from, address to, uint value, bytes calldata data, bytes calldata operatorData) external override {
require(interfaceAddr(msg.sender, "ERC1400Token") == msg.sender, "55"); // 0x55 funds locked (lockup period)
require(to == address(this), "50"); // 0x50 transfer failure
require(_canReceive(data, operatorData), "57"); // 0x57 invalid receiver
bytes32 flag = _getTransferFlag(data);
bytes memory erc1400TokenData = abi.encode(msg.sender, partition, value);
if (flag == ORDER_SUBSCRIPTION_FLAG) {
address assetAddress = _getAssetAddress(data);
bytes32 assetClass = _getAssetClass(data);
bytes memory orderData = _getOrderData(data);
_subscribe(
from,
assetAddress,
assetClass,
orderData,
true,
erc1400TokenData
);
} else if (flag == ORDER_PAYMENT_FLAG) {
uint256 orderIndex = _getOrderIndex(data);
Order storage order = _orders[orderIndex];
require(from == order.investor, "Payment sender is not the subscriber");
_executePayment(orderIndex, erc1400TokenData, false);
}
}
/**
* @dev Start a new subscription for a given asset in the fund issuance smart contract.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @param subscriptionPeriodLength Length of subscription period.
* @param valuationPeriodLength Length of valuation period.
* @param paymentPeriodLength Length of payment period.
* @param paymentType Type of payment (OFFCHAIN | ERC20 | ERC1400).
* @param paymentAddress Address of the payment token (only used id paymentType <> OFFCHAIN).
* @param paymentPartition Partition of the payment token (only used if paymentType is ERC1400).
* @param subscriptionsOpened Set 'true' if subscriptions are opened, 'false' if not.
*/
function setAssetRules(
address assetAddress,
bytes32 assetClass,
uint256 firstStartTime,
uint256 subscriptionPeriodLength,
uint256 valuationPeriodLength,
uint256 paymentPeriodLength,
Payment paymentType,
address paymentAddress,
bytes32 paymentPartition,
address fundAddress,
bool subscriptionsOpened
)
external
onlyTokenController(assetAddress)
{
AssetRules storage rules = _assetRules[assetAddress][assetClass];
require(firstStartTime >= block.timestamp, "First cycle start can not be prior to now");
require(subscriptionPeriodLength != 0 && valuationPeriodLength != 0 && paymentPeriodLength != 0, "Periods can not be nil");
if(rules.defined) {
rules.firstStartTime = firstStartTime;
rules.subscriptionPeriodLength = subscriptionPeriodLength;
rules.valuationPeriodLength = valuationPeriodLength;
rules.paymentPeriodLength = paymentPeriodLength;
// rules.assetValueType = assetValueType; // Can only be modified by the price oracle
// rules.assetValue = assetValue; // Can only be modified by the price oracle
// rules.reverseAssetValue = reverseAssetValue; // Can only be modified by the price oracle
rules.paymentType = paymentType;
rules.paymentAddress = paymentAddress;
rules.paymentPartition = paymentPartition;
rules.fundAddress = fundAddress;
rules.subscriptionsOpened = subscriptionsOpened;
} else {
_assetRules[assetAddress][assetClass] = AssetRules({
defined: true,
firstStartTime: firstStartTime,
subscriptionPeriodLength: subscriptionPeriodLength,
valuationPeriodLength: valuationPeriodLength,
paymentPeriodLength: paymentPeriodLength,
assetValueType: AssetValue.Unknown,
assetValue: 0,
reverseAssetValue: 0,
paymentType: paymentType,
paymentAddress: paymentAddress,
paymentPartition: paymentPartition,
fundAddress: fundAddress,
subscriptionsOpened: subscriptionsOpened
});
}
}
/**
* @dev Set asset value rules for a given asset.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @param assetValueType Asset value type.
* @param assetValue Asset value.
* @param reverseAssetValue Reverse asset value.
*/
function setAssetValueRules(
address assetAddress,
bytes32 assetClass,
AssetValue assetValueType,
uint256 assetValue,
uint256 reverseAssetValue
)
external
onlyPriceOracle(assetAddress)
{
AssetRules storage rules = _assetRules[assetAddress][assetClass];
require(rules.defined, "Rules not defined for this asset");
require(assetValue == 0 || reverseAssetValue == 0, "Asset value can only be set in one direction");
rules.assetValueType = assetValueType;
rules.assetValue = assetValue;
rules.reverseAssetValue = reverseAssetValue;
}
/**
* @dev Start a new subscription for a given asset in the fund issuance smart contract.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @return Index of new cycle.
*/
function _startNewCycle(
address assetAddress,
bytes32 assetClass
)
internal
returns(uint256)
{
AssetRules storage rules = _assetRules[assetAddress][assetClass];
require(rules.defined, "Rules not defined for this asset");
require(rules.subscriptionsOpened, "Subscriptions not opened for this asset");
uint256 lastCycleIndex = _lastCycleIndex[assetAddress][assetClass];
Cycle storage lastCycle = _cycles[lastCycleIndex];
uint256 previousStartTime = (lastCycle.startTime != 0) ? lastCycle.startTime : rules.firstStartTime;
_cycleIndex = _cycleIndex.add(1);
_cycles[_cycleIndex] = Cycle({
assetAddress: assetAddress,
assetClass: assetClass,
startTime: _getNextStartTime(previousStartTime, rules.subscriptionPeriodLength),
subscriptionPeriodLength: rules.subscriptionPeriodLength,
valuationPeriodLength: rules.valuationPeriodLength,
paymentPeriodLength: rules.paymentPeriodLength,
assetValueType: rules.assetValueType,
assetValue: rules.assetValue,
reverseAssetValue: rules.reverseAssetValue,
paymentType: rules.paymentType,
paymentAddress: rules.paymentAddress,
paymentPartition: rules.paymentPartition,
fundAddress: rules.fundAddress,
finalized: false
});
_lastCycleIndex[assetAddress][assetClass] = _cycleIndex;
return _cycleIndex;
}
/**
* @dev Returns time of next cycle start.
* @param previousStartTime Previous start time.
* @param subscriptionPeriod Time between subscription period start and cut-off.
* @return Time of next cycle start.
*/
function _getNextStartTime(uint256 previousStartTime, uint256 subscriptionPeriod) internal view returns(uint256) {
if(previousStartTime >= block.timestamp) {
return previousStartTime;
} else {
return block.timestamp.sub((block.timestamp - previousStartTime).mod(subscriptionPeriod));
}
}
/**
* @dev Subscribe for a given asset, by creating an order.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @param orderValue Value of assets to purchase (used in case order type is 'value').
* @param orderAmount Amount of assets to purchase (used in case order type is 'amount').
* @param orderType Order type (value | amount).
*/
function subscribe(
address assetAddress,
bytes32 assetClass,
uint256 orderValue,
uint256 orderAmount,
OrderType orderType,
bool executePaymentAtSubscription
)
external
payable
returns(uint256)
{
bytes memory orderData = abi.encode(orderValue, orderAmount, orderType);
return _subscribe(
msg.sender,
assetAddress,
assetClass,
orderData,
executePaymentAtSubscription,
new bytes(0)
);
}
/**
* @dev Subscribe for a given asset, by creating an order.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @param orderData Encoded pack of variables for order (orderValue, orderAmount, orderType).
* @param executePaymentAtSubscription 'true' if payment shall be executed at subscription, 'false' if not.
* @param erc1400TokenData Encoded pack of variables for erc1400 token (paymentAddress, paymentPartition, paymentValue).
*/
function _subscribe(
address investor,
address assetAddress,
bytes32 assetClass,
bytes memory orderData,
bool executePaymentAtSubscription,
bytes memory erc1400TokenData
)
internal
returns(uint256)
{
uint256 lastIndex = _lastCycleIndex[assetAddress][assetClass];
CycleState currentState = _getCycleState(lastIndex);
if(currentState != CycleState.Subscription) {
lastIndex = _startNewCycle(assetAddress, assetClass);
}
require(_getCycleState(lastIndex) == CycleState.Subscription, "Subscription can only be performed during subscription period");
(uint256 value, uint256 amount, OrderType orderType) = abi.decode(orderData, (uint256, uint256, OrderType));
require(value == 0 || amount == 0, "Order can not be of type amount and value at the same time");
if(orderType == OrderType.Value) {
require(value != 0, "Order value shall not be nil");
} else if(orderType == OrderType.Amount) {
require(amount != 0, "Order amount shall not be nil");
} else {
revert("Order type needs to be value or amount");
}
_orderIndex++;
_orders[_orderIndex] = Order({
cycleIndex: lastIndex,
investor: investor,
value: value,
amount: amount,
orderType: orderType,
state: OrderState.Subscribed
});
_cycleOrders[lastIndex].push(_orderIndex);
_investorOrders[investor].push(_orderIndex);
Cycle storage cycle = _cycles[lastIndex];
if(cycle.assetValueType == AssetValue.Known && executePaymentAtSubscription) {
_executePayment(_orderIndex, erc1400TokenData, false);
}
return _orderIndex;
}
/**
* @dev Cancel an order.
* @param orderIndex Index of the order to cancel.
*/
function cancelOrder(uint256 orderIndex) external {
Order storage order = _orders[orderIndex];
require(
order.state == OrderState.Subscribed ||
order.state == OrderState.Paid,
"Only subscribed or paid orders can be cancelled"
); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined"
require(_getCycleState(order.cycleIndex) < CycleState.Valuation, "Orders can only be cancelled before cut-off");
require(msg.sender == order.investor);
if(order.state == OrderState.Paid) {
_releasePayment(orderIndex, order.investor);
}
order.state = OrderState.Cancelled;
}
/**
* @dev Reject an order.
* @param orderIndex Index of the order to reject.
* @param rejected Set to 'true' if order shall be rejected, and set to 'false' if rejection shall be cancelled
*/
function rejectOrder(uint256 orderIndex, bool rejected)
external
{
Order storage order = _orders[orderIndex];
require(
order.state == OrderState.Subscribed ||
order.state == OrderState.Paid ||
order.state == OrderState.Rejected
,
"Order rejection can only handled for subscribed or paid orders"
); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined"
require(_getCycleState(order.cycleIndex) < CycleState.Payment , "Orders can only be rejected before beginning of payment phase");
Cycle storage cycle = _cycles[order.cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
if(rejected) {
if(order.state == OrderState.Paid) {
_releasePayment(orderIndex, order.investor);
}
order.state = OrderState.Rejected;
} else {
order.state = OrderState.Subscribed;
}
}
/**
* @dev Set assetValue for a given asset.
* @param cycleIndex Index of the cycle where assetValue needs to be set.
* @param assetValue Units of cash required for a unit of asset.
* @param reverseAssetValue Units of asset required for a unit of cash.
*/
function valuate(
uint256 cycleIndex,
uint256 assetValue,
uint256 reverseAssetValue
)
external
{
Cycle storage cycle = _cycles[cycleIndex];
CycleState cycleState = _getCycleState(cycleIndex);
require(cycleState > CycleState.Subscription && cycleState < CycleState.Payment , "AssetValue can only be set during valuation period");
require(cycle.assetValueType == AssetValue.Unknown, "Asset value can only be set for a cycle of type unkonwn");
require(assetValue == 0 || reverseAssetValue == 0, "Asset value can only be set in one direction");
require(_checkPriceOracle(cycle.assetAddress, msg.sender), "Sender is not a price oracle.");
cycle.assetValue = assetValue;
cycle.reverseAssetValue = reverseAssetValue;
}
/**
* @dev Execute payment for a given order.
* @param orderIndex Index of the order to declare as paid.
*/
function executePaymentAsInvestor(uint256 orderIndex) external payable {
Order storage order = _orders[orderIndex];
require(msg.sender == order.investor);
_executePayment(orderIndex, new bytes(0), false);
}
/**
* @dev Set payment as executed for a given order.
* @param orderIndex Index of the order to declare as paid.
* @param bypassPayment Bypass payment (in case payment has been performed off-chain)
*/
function executePaymentAsController(uint256 orderIndex, bool bypassPayment) external {
Order storage order = _orders[orderIndex];
Cycle storage cycle = _cycles[order.cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
_executePayment(orderIndex, new bytes(0), bypassPayment);
}
/**
* @dev Set payments as executed for a batch of given orders.
* @param orderIndexes Indexes of the orders to declare as paid.
* @param bypassPayment Bypass payment (in case payment has been performed off-chain)
*/
function batchExecutePaymentsAsController(uint256[] calldata orderIndexes, bool bypassPayment)
external
{
for (uint i = 0; i<orderIndexes.length; i++){
Order storage order = _orders[orderIndexes[i]];
Cycle storage cycle = _cycles[order.cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
_executePayment(orderIndexes[i], new bytes(0), bypassPayment);
}
}
/**
* @dev Pay for a given order.
* @param orderIndex Index of the order to declare as paid.
* @param erc1400TokenData Encoded pack of variables for erc1400 token (paymentAddress, paymentPartition, paymentValue).
* @param bypassPayment Bypass payment (in case payment has been performed off-chain)
*/
function _executePayment(
uint256 orderIndex,
bytes memory erc1400TokenData,
bool bypassPayment
)
internal
{
Order storage order = _orders[orderIndex];
Cycle storage cycle = _cycles[order.cycleIndex];
require(
order.state == OrderState.Subscribed ||
order.state == OrderState.UnpaidSettled,
"Order is neither in state Subscribed, nor UnpaidSettled"
); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined"
require(!cycle.finalized, "Cycle is already finalized");
if(cycle.assetValueType == AssetValue.Unknown) {
require(_getCycleState(order.cycleIndex) >= CycleState.Payment , "Payment can only be performed after valuation period");
} else {
require(_getCycleState(order.cycleIndex) >= CycleState.Subscription , "Payment can only be performed after start of subscription period");
}
require(order.orderType == OrderType.Value || order.orderType == OrderType.Amount, "Invalid order type");
(uint256 amount, uint256 value) = _getOrderAmountAndValue(orderIndex);
order.amount = amount;
order.value = value;
if(!bypassPayment) {
if (cycle.paymentType == Payment.ETH) {
require(msg.value == value, "Amount of ETH is not correct");
_escrowedEth[cycle.assetAddress] += value;
} else if (cycle.paymentType == Payment.ERC20) {
ERC20(cycle.paymentAddress).transferFrom(msg.sender, address(this), value);
_escrowedErc20[cycle.assetAddress][cycle.paymentAddress] += value;
} else if(cycle.paymentType == Payment.ERC1400 && erc1400TokenData.length == 0) {
ERC1400(cycle.paymentAddress).operatorTransferByPartition(cycle.paymentPartition, msg.sender, address(this), value, abi.encodePacked(BYPASS_ACTION_FLAG), abi.encodePacked(BYPASS_ACTION_FLAG));
_escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] += value;
} else if(cycle.paymentType == Payment.ERC1400 && erc1400TokenData.length != 0) {
(address erc1400TokenAddress, bytes32 erc1400TokenPartition, uint256 erc1400PaymentValue) = abi.decode(erc1400TokenData, (address, bytes32, uint256));
require(erc1400PaymentValue == value, "wrong payment value");
require(Payment.ERC1400 == cycle.paymentType, "ERC1400 payment is not accecpted for this asset");
require(erc1400TokenAddress == cycle.paymentAddress, "wrong payment token address");
require(erc1400TokenPartition == cycle.paymentPartition, "wrong payment token partition");
_escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] += value;
} else {
revert("off-chain payment needs to be bypassed");
}
}
if(order.state == OrderState.UnpaidSettled) {
_releasePayment(orderIndex, cycle.fundAddress);
order.state = OrderState.PaidSettled;
} else {
order.state = OrderState.Paid;
}
}
/**
* @dev Retrieve order amount and order value calculated based on cycle valuation.
* @param orderIndex Index of the order.
* @return Order amount.
* @return Order value.
*/
function _getOrderAmountAndValue(uint256 orderIndex) internal view returns(uint256, uint256) {
Order storage order = _orders[orderIndex];
Cycle storage cycle = _cycles[order.cycleIndex];
uint256 value;
uint256 amount;
if(order.orderType == OrderType.Value) {
value = order.value;
if(cycle.assetValue != 0) {
amount = value.div(cycle.assetValue);
} else {
amount = value.mul(cycle.reverseAssetValue);
}
}
if(order.orderType == OrderType.Amount) {
amount = order.amount;
if(cycle.assetValue != 0) {
value = amount.mul(cycle.assetValue);
} else {
value = amount.div(cycle.reverseAssetValue);
}
}
return(amount, value);
}
/**
* @dev Release payment for a given order.
* @param orderIndex Index of the order of the payment to be sent.
* @param recipient Address to receive to the payment.
*/
function _releasePayment(uint256 orderIndex, address recipient) internal {
Order storage order = _orders[orderIndex];
Cycle storage cycle = _cycles[order.cycleIndex];
if(cycle.paymentType == Payment.ETH) {
address payable refundAddress = payable(recipient);
refundAddress.transfer(order.value);
_escrowedEth[cycle.assetAddress] -= order.value;
} else if(cycle.paymentType == Payment.ERC20) {
ERC20(cycle.paymentAddress).transfer(recipient, order.value);
_escrowedErc20[cycle.assetAddress][cycle.paymentAddress] -= order.value;
} else if(cycle.paymentType == Payment.ERC1400) {
ERC1400(cycle.paymentAddress).transferByPartition(cycle.paymentPartition, recipient, order.value, abi.encodePacked(BYPASS_ACTION_FLAG));
_escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] -= order.value;
}
}
/**
* @dev Settle a given order.
* @param orderIndex Index of the order to settle.
*/
function settleOrder(uint256 orderIndex) internal {
Order storage order = _orders[orderIndex];
Cycle storage cycle = _cycles[order.cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
_settleOrder(orderIndex);
}
/**
* @dev Settle a batch of given orders.
* @param orderIndexes Indexes of the orders to settle.
*/
function batchSettleOrders(uint256[] calldata orderIndexes)
external
{
for (uint i = 0; i<orderIndexes.length; i++){
Order storage order = _orders[orderIndexes[i]];
Cycle storage cycle = _cycles[order.cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
_settleOrder(orderIndexes[i]);
}
}
/**
* @dev Settle a given order.
* @param orderIndex Index of the order to settle.
*/
function _settleOrder(uint256 orderIndex) internal {
Order storage order = _orders[orderIndex];
require(order.state > OrderState.Undefined, "Order doesnt exist");
CycleState currentState = _getCycleState(order.cycleIndex);
Cycle storage cycle = _cycles[order.cycleIndex];
if(cycle.assetValueType == AssetValue.Unknown) {
require(currentState >= CycleState.Settlement, "Order settlement can only be performed during settlement period");
} else {
require(currentState >= CycleState.Valuation, "Order settlement can only be performed after the cut-off");
}
_releasePayment(orderIndex, cycle.fundAddress);
if(order.state == OrderState.Paid) {
ERC1400(cycle.assetAddress).issueByPartition(cycle.assetClass, order.investor, order.amount, "");
order.state = OrderState.PaidSettled;
} else if (order.state == OrderState.Subscribed) {
ERC1400(cycle.assetAddress).issueByPartition(cycle.assetClass, address(this), order.amount, "");
order.state = OrderState.UnpaidSettled;
} else {
revert("Impossible to settle an order that is neither in state Paid, nor Subscribed");
}
}
/**
* @dev Finalize a given cycle.
* @param cycleIndex Index of the cycle to finalize.
*/
function finalizeCycle(uint256 cycleIndex) external {
Cycle storage cycle = _cycles[cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
require(!cycle.finalized, "Cycle is already finalized");
(, uint256 totalUnpaidSettled, bool remainingOrdersToSettle) = _getTotalSettledForCycle(cycleIndex);
if(!remainingOrdersToSettle) {
cycle.finalized = true;
if(totalUnpaidSettled != 0) {
ERC1400(cycle.assetAddress).transferByPartition(cycle.assetClass, cycle.fundAddress, totalUnpaidSettled, "");
}
} else {
revert("Remaining orders to settle");
}
}
/**
* @dev Retrieve sum of paid/unpaid settled orders for a given cycle.
*
* @param cycleIndex Index of the cycle.
* @return Sum of paid settled orders.
* @return Sum of unpaid settled orders.
* @return 'True' if there are remaining orders to settle, 'false' if not.
*/
function getTotalSettledForCycle(uint256 cycleIndex) external view returns(uint256, uint256, bool) {
return _getTotalSettledForCycle(cycleIndex);
}
/**
* @dev Retrieve sum of paid/unpaid settled orders for a given cycle.
*
* @param cycleIndex Index of the cycle.
* @return Sum of paid settled orders.
* @return Sum of unpaid settled orders.
* @return 'True' if there are remaining orders to settle, 'false' if not.
*/
function _getTotalSettledForCycle(uint256 cycleIndex) internal view returns(uint256, uint256, bool) {
uint256 totalPaidSettled;
uint256 totalUnpaidSettled;
bool remainingOrdersToSettle;
for (uint i = 0; i<_cycleOrders[cycleIndex].length; i++){
Order storage order = _orders[_cycleOrders[cycleIndex][i]];
if(order.state == OrderState.PaidSettled) {
totalPaidSettled = totalPaidSettled.add(order.amount);
} else if(order.state == OrderState.UnpaidSettled) {
totalUnpaidSettled = totalUnpaidSettled.add(order.amount);
} else if(
order.state != OrderState.Cancelled &&
order.state != OrderState.Rejected
) {
remainingOrdersToSettle = true;
}
}
return (totalPaidSettled, totalUnpaidSettled, remainingOrdersToSettle);
}
/**
* @dev Retrieve the current state of the cycle.
*
* @param cycleIndex Index of the cycle.
* @return Cycle state.
*/
function getCycleState(uint256 cycleIndex) external view returns(CycleState) {
return _getCycleState(cycleIndex);
}
/**
* @dev Retrieve the current state of the cycle.
*
* @param cycleIndex Index of the cycle.
* @return Cycle state.
*/
function _getCycleState(uint256 cycleIndex) internal view returns(CycleState) {
Cycle storage cycle = _cycles[cycleIndex];
if(block.timestamp < cycle.startTime || cycle.startTime == 0) {
return CycleState.Undefined;
} else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength) {
return CycleState.Subscription;
} else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength + cycle.valuationPeriodLength) {
return CycleState.Valuation;
} else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength + cycle.valuationPeriodLength + cycle.paymentPeriodLength) {
return CycleState.Payment;
} else if(!cycle.finalized){
return CycleState.Settlement;
} else {
return CycleState.Finalized;
}
}
/**
* @dev Check if the sender is a token controller.
*
* @param sender Transaction sender.
* @param assetAddress Address of the token representing the asset.
* @return Returns 'true' if sender is a token controller.
*/
function _tokenController(address sender, address assetAddress) internal view returns(bool) {
if(sender == Ownable(assetAddress).owner() ||
_isTokenController[assetAddress][sender]) {
return true;
} else {
return false;
}
}
/**
* @dev Indicate whether or not the fund issuance contract can receive the tokens.
*
* By convention, the 32 first bytes of a token transfer to the fund issuance smart contract contain a flag.
*
* - When tokens are transferred to fund issuance contract to create a new order, the 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* In this case the data structure is the the following:
* <transferFlag (32 bytes)><asset address (32 bytes)><asset class (32 bytes)><order data (3 * 32 bytes)>
*
* - When tokens are transferred to fund issuance contract to pay for an existing order, the 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
* In this case the data structure is the the following:
* <transferFlag (32 bytes)><order index (32 bytes)>
*
* If the 'data' doesn't start with one of those flags, the fund issuance contract won't accept the token transfer.
*
* @param data Information attached to the token transfer to fund issuance contract.
* @param operatorData Information attached to the token transfer to fund issuance contract, by the operator.
* @return 'true' if the fund issuance contract can receive the tokens, 'false' if not.
*/
function _canReceive(bytes memory data, bytes memory operatorData) internal pure returns(bool) {
if(operatorData.length == 0) { // The reason for this check is to avoid a certificate gets interpreted as a flag by mistake
return false;
}
bytes32 flag = _getTransferFlag(data);
if(data.length == 192 && flag == ORDER_SUBSCRIPTION_FLAG) {
return true;
} else if(data.length == 64 && flag == ORDER_PAYMENT_FLAG) {
return true;
} else if (data.length == 32 && flag == BYPASS_ACTION_FLAG) {
return true;
} else {
return false;
}
}
/**
* @dev Retrieve the transfer flag from the 'data' field.
*
* By convention, the 32 first bytes of a token transfer to the fund issuance smart contract contain a flag.
* - When tokens are transferred to fund issuance contract to create a new order, the 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* - When tokens are transferred to fund issuance contract to pay for an existing order, the 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* @param data Concatenated information about the transfer.
* @return flag Transfer flag.
*/
function _getTransferFlag(bytes memory data) internal pure returns(bytes32 flag) {
assembly {
flag:= mload(add(data, 32))
}
}
/**
* By convention, when tokens are transferred to fund issuance contract to create a new order, the 'data' of a token transfer has the following structure:
* <transferFlag (32 bytes)><asset address (32 bytes)><asset class (32 bytes)><order data (3 * 32 bytes)>
*
* The first 32 bytes are the flag 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
*
* The next 32 bytes contain the order index.
*
* Example input for asset address '0xb5747835141b46f7C472393B31F8F5A57F74A44f',
* asset class '37252', order type 'Value', and value 12000
* 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc000000000000000000000000b5747835141b46f7C472393B31F8F5A57F74A44f
* 000000000000000000000000000000000000000000000000000000000037252000000000000000000000000000000000000000000000000000000000000001
* 000000000000000000000000000000000000000000000000000000000002ee0000000000000000000000000000000000000000000000000000000000000000
*
*/
function _getAssetAddress(bytes memory data) internal pure returns(address assetAddress) {
assembly {
assetAddress:= mload(add(data, 64))
}
}
function _getAssetClass(bytes memory data) internal pure returns(bytes32 assetClass) {
assembly {
assetClass:= mload(add(data, 96))
}
}
function _getOrderData(bytes memory data) internal pure returns(bytes memory orderData) {
uint256 orderValue;
uint256 orderAmount;
OrderType orderType;
assembly {
orderValue:= mload(add(data, 128))
orderAmount:= mload(add(data, 160))
orderType:= mload(add(data, 192))
}
orderData = abi.encode(orderValue, orderAmount, orderType);
}
/**
* By convention, when tokens are transferred to fund issuance contract to pay for an existing order, the 'data' of a token transfer has the following structure:
* <transferFlag (32 bytes)><order index (32 bytes)>
*
* The first 32 bytes are the flag 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* The next 32 bytes contain the order index.
*
* Example input for order index 3:
* 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd000000000000000000000000000000000000000000000000000000000000003
*
*/
/**
* @dev Retrieve the order index from the 'data' field.
*
* @param data Concatenated information about the order payment.
* @return orderIndex Order index.
*/
function _getOrderIndex(bytes memory data) internal pure returns(uint256 orderIndex) {
assembly {
orderIndex:= mload(add(data, 64))
}
}
/************************** TOKEN CONTROLLERS *******************************/
/**
* @dev Get the list of token controllers for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the token controllers for a given token.
*/
function tokenControllers(address tokenAddress) external view returns (address[] memory) {
return _tokenControllers[tokenAddress];
}
/**
* @dev Set list of token controllers for a given token.
* @param tokenAddress Token address.
* @param operators Operators addresses.
*/
function setTokenControllers(address tokenAddress, address[] calldata operators) external onlyTokenController(tokenAddress) {
_setTokenControllers(tokenAddress, operators);
}
/**
* @dev Set list of token controllers for a given token.
* @param tokenAddress Token address.
* @param operators Operators addresses.
*/
function _setTokenControllers(address tokenAddress, address[] memory operators) internal {
for (uint i = 0; i<_tokenControllers[tokenAddress].length; i++){
_isTokenController[tokenAddress][_tokenControllers[tokenAddress][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTokenController[tokenAddress][operators[j]] = true;
}
_tokenControllers[tokenAddress] = operators;
}
/************************** TOKEN PRICE ORACLES *******************************/
/**
* @dev Get the list of price oracles for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the price oracles for a given token.
*/
function priceOracles(address tokenAddress) external view returns (address[] memory) {
return _priceOracles[tokenAddress];
}
/**
* @dev Set list of price oracles for a given token.
* @param tokenAddress Token address.
* @param oracles Oracles addresses.
*/
function setPriceOracles(address tokenAddress, address[] calldata oracles) external onlyPriceOracle(tokenAddress) {
_setPriceOracles(tokenAddress, oracles);
}
/**
* @dev Set list of price oracles for a given token.
* @param tokenAddress Token address.
* @param oracles Oracles addresses.
*/
function _setPriceOracles(address tokenAddress, address[] memory oracles) internal {
for (uint i = 0; i<_priceOracles[tokenAddress].length; i++){
_isPriceOracle[tokenAddress][_priceOracles[tokenAddress][i]] = false;
}
for (uint j = 0; j<oracles.length; j++){
_isPriceOracle[tokenAddress][oracles[j]] = true;
}
_priceOracles[tokenAddress] = oracles;
}
/**
* @dev Check if address is oracle of a given token.
* @param tokenAddress Token address.
* @param oracle Oracle address.
* @return 'true' if the address is oracle of the given token.
*/
function _checkPriceOracle(address tokenAddress, address oracle) internal view returns(bool) {
return(_isPriceOracle[tokenAddress][oracle] || oracle == Ownable(tokenAddress).owner());
}
/**************************** VIEW FUNCTIONS *******************************/
/**
* @dev Get asset rules.
* @param assetAddress Address of the asset.
* @param assetClass Class of the asset.
* @return Asset rules.
*/
function getAssetRules(address assetAddress, bytes32 assetClass)
external
view
returns(uint256, uint256, uint256, uint256, Payment, address, bytes32, address, bool)
{
AssetRules storage rules = _assetRules[assetAddress][assetClass];
return (
rules.firstStartTime,
rules.subscriptionPeriodLength,
rules.valuationPeriodLength,
rules.paymentPeriodLength,
rules.paymentType,
rules.paymentAddress,
rules.paymentPartition,
rules.fundAddress,
rules.subscriptionsOpened
);
}
/**
* @dev Get the cycle asset value rules.
* @param assetAddress Address of the asset.
* @param assetClass Class of the asset.
* @return Asset value rules.
*/
function getAssetValueRules(address assetAddress, bytes32 assetClass) external view returns(AssetValue, uint256, uint256) {
AssetRules storage rules = _assetRules[assetAddress][assetClass];
return (
rules.assetValueType,
rules.assetValue,
rules.reverseAssetValue
);
}
/**
* @dev Get total number of cycles in the contract.
* @return Number of cycles.
*/
function getNbCycles() external view returns(uint256) {
return _cycleIndex;
}
/**
* @dev Get the index of the last cycle created for a given asset class.
* @param assetAddress Address of the token representing the asset.
* @param assetClass Asset class.
* @return Cycle index.
*/
function getLastCycleIndex(address assetAddress, bytes32 assetClass) external view returns(uint256) {
return _lastCycleIndex[assetAddress][assetClass];
}
/**
* @dev Get the cycle.
* @param index Index of the cycle.
* @return Cycle.
*/
function getCycle(uint256 index) external view returns(address, bytes32, uint256, uint256, uint256, uint256, Payment, address, bytes32, bool) {
Cycle storage cycle = _cycles[index];
return (
cycle.assetAddress,
cycle.assetClass,
cycle.startTime,
cycle.subscriptionPeriodLength,
cycle.valuationPeriodLength,
cycle.paymentPeriodLength,
cycle.paymentType,
cycle.paymentAddress,
cycle.paymentPartition,
cycle.finalized
);
}
/**
* @dev Get the cycle asset value.
* @param index Index of the cycle.
* @return Cycle.
*/
function getCycleAssetValue(uint256 index) external view returns(AssetValue, uint256, uint256) {
Cycle storage cycle = _cycles[index];
return (
cycle.assetValueType,
cycle.assetValue,
cycle.reverseAssetValue
);
}
/**
* @dev Get total number of orders in the contract.
* @return Number of orders.
*/
function getNbOrders() external view returns(uint256) {
return _orderIndex;
}
/**
* @dev Retrieve an order.
* @param index Index of the order.
* @return Order.
*/
function getOrder(uint256 index) external view returns(uint256, address, uint256, uint256, OrderType, OrderState) {
Order storage order = _orders[index];
return (
order.cycleIndex,
order.investor,
order.value,
order.amount,
order.orderType,
order.state
);
}
/**
* @dev Retrieve order amount and order value calculated based on cycle valuation.
* @param orderIndex Index of the order.
* @return Order amount.
* @return Order value.
*/
function getOrderAmountAndValue(uint256 orderIndex) external view returns(uint256, uint256) {
return _getOrderAmountAndValue(orderIndex);
}
/**
* @dev Get list of cycle orders.
* @param index Index of the cycle.
* @return List of cycle orders.
*/
function getCycleOrders(uint256 index) external view returns(uint256[] memory) {
return _cycleOrders[index];
}
/**
* @dev Get list of investor orders.
* @return List of investor orders.
*/
function getInvestorOrders(address investor) external view returns(uint256[] memory) {
return _investorOrders[investor];
}
}
| Finalize a given cycle. cycleIndex Index of the cycle to finalize./ | function finalizeCycle(uint256 cycleIndex) external {
Cycle storage cycle = _cycles[cycleIndex];
require(_tokenController(msg.sender, cycle.assetAddress),
"Sender is not a token controller."
);
require(!cycle.finalized, "Cycle is already finalized");
(, uint256 totalUnpaidSettled, bool remainingOrdersToSettle) = _getTotalSettledForCycle(cycleIndex);
if(!remainingOrdersToSettle) {
cycle.finalized = true;
if(totalUnpaidSettled != 0) {
ERC1400(cycle.assetAddress).transferByPartition(cycle.assetClass, cycle.fundAddress, totalUnpaidSettled, "");
}
revert("Remaining orders to settle");
}
}
| 5,531,065 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./WhiteRabbitProducerPass.sol";
contract WhiteRabbit is Ownable, ERC1155Holder {
using Strings for uint256;
using SafeMath for uint256;
// The Producer Pass contract used for staking/voting on episodes
WhiteRabbitProducerPass private whiteRabbitProducerPass;
// The total number of episodes that make up the film
uint256 private _numberOfEpisodes;
// A mapping from episodeId to whether or not voting is enabled
mapping(uint256 => bool) public votingEnabledForEpisode;
// The address of the White Rabbit token ($WRAB)
address public whiteRabbitTokenAddress;
// The initial fixed supply of White Rabbit tokens
uint256 public tokenInitialFixedSupply;
// The wallet addresses of the two artists creating the film
address private _artist1Address;
address private _artist2Address;
// The percentage of White Rabbit tokens that will go to the artists
uint256 public artistTokenAllocationPercentage;
// The number of White Rabbit tokens to send to each artist per episode
uint256 public artistTokenPerEpisodePerArtist;
// A mapping from episodeId to a boolean indicating whether or not
// White Rabbit tokens have been transferred the artists yet
mapping(uint256 => bool) public hasTransferredTokensToArtistForEpisode;
// The percentage of White Rabbit tokens that will go to producers (via Producer Pass staking)
uint256 public producersTokenAllocationPercentage;
// The number of White Rabbit tokens to send to producers per episode
uint256 public producerPassTokenAllocationPerEpisode;
// The base number of White Rabbit tokens to allocate to producers per episode
uint256 public producerPassTokenBaseAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake early
uint256 public producerPassTokenEarlyStakingBonusAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake for the winning option
uint256 public producerPassTokenWinningBonusAllocationPerEpisode;
// The percentage of White Rabbit tokens that will go to the platform team
uint256 public teamTokenAllocationPercentage;
// Whether or not the team has received its share of White Rabbit tokens
bool public teamTokenAllocationDistributed;
// Event emitted when a Producer Pass is staked to vote for an episode option
event ProducerPassStaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 amount,
uint256 tokenAmount
);
// Event emitted when a Producer Pass is unstaked after voting is complete
event ProducerPassUnstaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 tokenAmount
);
// The list of episode IDs (e.g. [1, 2, 3, 4])
uint256[] public episodes;
// The voting option IDs by episodeId (e.g. 1 => [1, 2])
mapping(uint256 => uint256[]) private _episodeOptions;
// The total vote counts for each episode voting option, agnostic of users
// _episodeVotesByOptionId[episodeId][voteOptionId] => number of votes
mapping(uint256 => mapping(uint256 => uint256))
private _episodeVotesByOptionId;
// A mapping from episodeId to the winning vote option
// 0 means no winner has been declared yet
mapping(uint256 => uint256) public winningVoteOptionByEpisode;
// A mapping of how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingOptionsCount[address][episodeId][voteOptionId] => number staked
// These values will be updated/decremented when Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingOptionsCount;
// A mapping of the *history* how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingHistoryCount[address][episodeId][voteOptionId] => number staked
// Note: These values DO NOT change after Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingHistoryCount;
// The base URI for episode metadata
string private _episodeBaseURI;
// The base URI for episode voting option metadata
string private _episodeOptionBaseURI;
/**
* @dev Initializes the contract by setting up the Producer Pass contract to be used
*/
constructor(address whiteRabbitProducerPassContract) {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the Producer Pass contract to be used
*/
function setWhiteRabbitProducerPassContract(
address whiteRabbitProducerPassContract
) external onlyOwner {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the base URI for episode metadata
*/
function setEpisodeBaseURI(string memory baseURI) external onlyOwner {
_episodeBaseURI = baseURI;
}
/**
* @dev Sets the base URI for episode voting option metadata
*/
function setEpisodeOptionBaseURI(string memory baseURI) external onlyOwner {
_episodeOptionBaseURI = baseURI;
}
/**
* @dev Sets the list of episode IDs (e.g. [1, 2, 3, 4])
*
* This will be updated every time a new episode is added.
*/
function setEpisodes(uint256[] calldata _episodes) external onlyOwner {
episodes = _episodes;
}
/**
* @dev Sets the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function setEpisodeOptions(
uint256 episodeId,
uint256[] calldata episodeOptionIds
) external onlyOwner {
require(episodeId <= episodes.length, "Episode does not exist");
_episodeOptions[episodeId] = episodeOptionIds;
}
/**
* @dev Retrieves the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getEpisodeOptions(uint256 episodeId)
public
view
returns (uint256[] memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
return _episodeOptions[episodeId];
}
/**
* @dev Retrieves the number of episodes currently available.
*/
function getCurrentEpisodeCount() external view returns (uint256) {
return episodes.length;
}
/**
* @dev Constructs the metadata URI for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function episodeURI(uint256 episodeId)
public
view
virtual
returns (string memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(baseURI, episodeId.toString(), ".json")
)
: "";
}
/**
* @dev Constructs the metadata URI for a given episode voting option.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The episode voting option ID is valid
*/
function episodeOptionURI(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (string memory)
{
// TODO: DRY up these requirements? ("Episode does not exist", "Invalid voting option")
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeOptionBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
_episodeOptionBaseURI,
episodeId.toString(),
"/",
episodeOptionId.toString(),
".json"
)
)
: "";
}
/**
* @dev Getter for the `_episodeBaseURI`
*/
function episodeBaseURI() internal view virtual returns (string memory) {
return _episodeBaseURI;
}
/**
* @dev Getter for the `_episodeOptionBaseURI`
*/
function episodeOptionBaseURI()
internal
view
virtual
returns (string memory)
{
return _episodeOptionBaseURI;
}
/**
* @dev Retrieves the voting results for a given episode's voting option ID
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is no longer enabled for the given episode
* - Voting has completed and a winning option has been declared
*/
function episodeVotes(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (uint256)
{
require(episodeId <= episodes.length, "Episode does not exist");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
require(
winningVoteOptionByEpisode[episodeId] > 0,
"Voting not finished"
);
return _episodeVotesByOptionId[episodeId][episodeOptionId];
}
/**
* @dev Retrieves the number of Producer Passes that the user has staked
* for a given episode and voting option at this point in time.
*
* Note that this number will change after a user has unstaked.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCount(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Retrieves the historical number of Producer Passes that the user
* has staked for a given episode and voting option.
*
* Note that this number will not change as a result of unstaking.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCountHistory(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Stakes Producer Passes for the given episode's voting option ID,
* with the ability to specify an `amount`. Staking is used to vote for the option
* that the user would like to see producers for the next episode.
*
* Emits a `ProducerPassStaked` event indicating that the staking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is enabled for the given episode
* - The user is attempting to stake more than zero Producer Passes
* - The user has enough Producer Passes to stake
* - The episode voting option is valid
* - A winning option hasn't been declared yet
*/
function stakeProducerPass(
uint256 episodeId,
uint256 voteOptionId,
uint256 amount
) public {
require(episodeId <= episodes.length, "Episode does not exist");
require(votingEnabledForEpisode[episodeId], "Voting not enabled");
require(amount > 0, "Cannot stake 0");
require(
whiteRabbitProducerPass.balanceOf(msg.sender, episodeId) >= amount,
"Insufficient pass balance"
);
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
// vote options should be [1, 2], ID <= length
require(
votingOptionsForThisEpisode.length >= voteOptionId,
"Invalid voting option"
);
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
// rely on winningVoteOptionId to determine that this episode is valid for voting on
require(winningVoteOptionId == 0, "Winner already declared");
// user's vote count for selected episode & option
uint256 userCurrentVoteCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
// Get total vote count of this option user is voting/staking for
uint256 currentTotalVoteCount = _episodeVotesByOptionId[episodeId][
voteOptionId
];
// Get total vote count from every option of this episode for bonding curve calculation
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// calculate token rewards here
uint256 tokensAllocated = getTokenAllocationForUserBeforeStaking(
episodeId,
amount
);
uint256 userNewVoteCount = userCurrentVoteCount + amount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_episodeVotesByOptionId[episodeId][voteOptionId] =
currentTotalVoteCount +
amount;
// Take custody of producer passes from user
whiteRabbitProducerPass.safeTransferFrom(
msg.sender,
address(this),
episodeId,
amount,
""
);
// Distribute wr tokens to user
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, tokensAllocated);
emit ProducerPassStaked(
msg.sender,
episodeId,
voteOptionId,
amount,
tokensAllocated
);
}
/**
* @dev Unstakes Producer Passes for the given episode's voting option ID and
* sends White Rabbit tokens to the user's wallet if they staked for the winning side.
*
*
* Emits a `ProducerPassUnstaked` event indicating that the unstaking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function unstakeProducerPasses(uint256 episodeId, uint256 voteOptionId)
public
{
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
uint256 stakedProducerPassCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
require(stakedProducerPassCount > 0, "No producer passes staked");
uint256 winningBonus = getUserWinningBonus(episodeId, voteOptionId) *
stakedProducerPassCount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = 0;
if (winningBonus > 0) {
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, winningBonus);
}
whiteRabbitProducerPass.safeTransferFrom(
address(this),
msg.sender,
episodeId,
stakedProducerPassCount,
""
);
emit ProducerPassUnstaked(
msg.sender,
episodeId,
voteOptionId,
winningBonus
);
}
/**
* @dev Calculates the number of White Rabbit tokens to award the user for unstaking
* their Producer Passes for a given episode's voting option ID.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function getUserWinningBonus(uint256 episodeId, uint256 episodeOptionId)
public
view
returns (uint256)
{
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
require(winningVoteOptionId > 0, "Voting is not finished");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
bool isWinningOption = winningVoteOptionId == episodeOptionId;
uint256 numberOfWinningVotes = _episodeVotesByOptionId[episodeId][
episodeOptionId
];
uint256 winningBonus = 0;
if (isWinningOption && numberOfWinningVotes > 0) {
winningBonus =
producerPassTokenWinningBonusAllocationPerEpisode /
numberOfWinningVotes;
}
return winningBonus;
}
/**
* @dev This method is only for the owner since we want to hide the voting results from the public
* until after voting has ended. Users can verify the veracity of this via the `episodeVotes` method
* which can be called publicly after voting has finished for an episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTotalVotesForEpisode(uint256 episodeId)
external
view
onlyOwner
returns (uint256[] memory)
{
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256[] memory totalVotes = new uint256[](
votingOptionsForThisEpisode.length
);
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
totalVotes[i] = votesForEpisode;
}
return totalVotes;
}
/**
* @dev Owner method to toggle the voting state of a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The voting state is different than the current state
* - A winning option has not yet been declared
*/
function setVotingEnabledForEpisode(uint256 episodeId, bool enabled)
public
onlyOwner
{
require(episodeId <= episodes.length, "Episode does not exist");
require(
votingEnabledForEpisode[episodeId] != enabled,
"Voting state unchanged"
);
// if winner already set, don't allow re-opening of voting
if (enabled) {
require(
winningVoteOptionByEpisode[episodeId] == 0,
"Winner for episode already set"
);
}
votingEnabledForEpisode[episodeId] = enabled;
}
/**
* @dev Sets up the distribution parameters for White Rabbit (WRAB) tokens.
*
* - We will create fractionalized NFT basket first, which will represent the finished film NFT
* - Tokens will be stored on platform and distributed to artists and producers as the film progresses
* - Artist distribution happens when new episodes are uploaded
* - Producer distribution happens when Producer Passes are staked and unstaked (with a bonus for winning the vote)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function startWhiteRabbitShowWithParams(
address tokenAddress,
address artist1Address,
address artist2Address,
uint256 numberOfEpisodes,
uint256 producersAllocationPercentage,
uint256 artistAllocationPercentage,
uint256 teamAllocationPercentage
) external onlyOwner {
require(
(producersAllocationPercentage +
artistAllocationPercentage +
teamAllocationPercentage) <= 100,
"Total percentage exceeds 100"
);
whiteRabbitTokenAddress = tokenAddress;
tokenInitialFixedSupply = IERC20(whiteRabbitTokenAddress).totalSupply();
_artist1Address = artist1Address;
_artist2Address = artist2Address;
_numberOfEpisodes = numberOfEpisodes;
producersTokenAllocationPercentage = producersAllocationPercentage;
artistTokenAllocationPercentage = artistAllocationPercentage;
teamTokenAllocationPercentage = teamAllocationPercentage;
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100 * 2) => 28571
artistTokenPerEpisodePerArtist =
(tokenInitialFixedSupply * artistTokenAllocationPercentage) /
(_numberOfEpisodes * 100 * 2); // 2 for 2 artists
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100) => 57142
producerPassTokenAllocationPerEpisode =
(tokenInitialFixedSupply * producersTokenAllocationPercentage) /
(_numberOfEpisodes * 100);
}
/**
* @dev Sets the White Rabbit (WRAB) token distrubution for producers.
* This distribution is broken into 3 categories:
* - Base allocation (every Producer Pass gets the same)
* - Early staking bonus (bonding curve distribution where earlier stakers are rewarded more)
* - Winning bonus (extra pot split among winning voters)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function setProducerPassWhiteRabbitTokensAllocationParameters(
uint256 earlyStakingBonus,
uint256 winningVoteBonus
) external onlyOwner {
require(
(earlyStakingBonus + winningVoteBonus) <= 100,
"Total percentage exceeds 100"
);
uint256 basePercentage = 100 - earlyStakingBonus - winningVoteBonus;
producerPassTokenBaseAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * basePercentage) /
100;
producerPassTokenEarlyStakingBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * earlyStakingBonus) /
100;
producerPassTokenWinningBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * winningVoteBonus) /
100;
}
/**
* @dev Calculates the number of White Rabbit tokens the user would receive if the
* provided `amount` of Producer Passes is staked for the given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTokenAllocationForUserBeforeStaking(
uint256 episodeId,
uint256 amount
) public view returns (uint256) {
ProducerPass memory pass = whiteRabbitProducerPass
.getEpisodeToProducerPass(episodeId);
uint256 maxSupply = pass.maxSupply;
uint256 basePerPass = SafeMath.div(
producerPassTokenBaseAllocationPerEpisode,
maxSupply
);
// Get total vote count from every option of this episode for bonding curve calculation
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// Below calculates number of tokens user will receive if staked
// using a linear bonding curve where early stakers get more
// Y = aX (where X = number of stakers, a = Slope, Y = tokens each staker receives)
uint256 maxBonusY = 1000 *
((producerPassTokenEarlyStakingBonusAllocationPerEpisode * 2) /
maxSupply);
uint256 slope = SafeMath.div(maxBonusY, maxSupply);
uint256 y1 = (slope * (maxSupply - totalVotesForEpisode));
uint256 y2 = (slope * (maxSupply - totalVotesForEpisode - amount));
uint256 earlyStakingBonus = (amount * (y1 + y2)) / 2;
return basePerPass * amount + earlyStakingBonus / 1000;
}
function endVotingForEpisode(uint256 episodeId) external onlyOwner {
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 winningOptionId = 0;
uint256 totalVotesForWinningOption = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentOptionId
];
if (votesForEpisode >= totalVotesForWinningOption) {
winningOptionId = currentOptionId;
totalVotesForWinningOption = votesForEpisode;
}
}
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* @dev Manually sets the winning voting option for a given episode.
* Only call this method to break a tie among voting options for an episode.
*
* Requirements:
*
* - This should only be called for ties
*/
function endVotingForEpisodeOverride(
uint256 episodeId,
uint256 winningOptionId
) external onlyOwner {
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* Token distribution for artists and team
*/
/**
* @dev Sends the artists their allocation of White Rabbit tokens after an episode is launched.
*
* Requirements:
*
* - The artists have not yet received their tokens for the given episode
*/
function sendArtistTokensForEpisode(uint256 episodeId) external onlyOwner {
require(
!hasTransferredTokensToArtistForEpisode[episodeId],
"Artist tokens distributed"
);
hasTransferredTokensToArtistForEpisode[episodeId] = true;
IERC20(whiteRabbitTokenAddress).transfer(
_artist1Address,
artistTokenPerEpisodePerArtist
);
IERC20(whiteRabbitTokenAddress).transfer(
_artist2Address,
artistTokenPerEpisodePerArtist
);
}
/**
* @dev Transfers White Rabbit tokens to the team based on the `teamTokenAllocationPercentage`
*
* Requirements:
*
* - The tokens have not yet been distributed to the team
*/
function withdrawTokensForTeamAllocation(address[] calldata teamAddresses)
external
onlyOwner
{
require(!teamTokenAllocationDistributed, "Team tokens distributed");
uint256 teamBalancePerMember = (teamTokenAllocationPercentage *
tokenInitialFixedSupply) / (100 * teamAddresses.length);
for (uint256 i = 0; i < teamAddresses.length; i++) {
IERC20(whiteRabbitTokenAddress).transfer(
teamAddresses[i],
teamBalancePerMember
);
}
teamTokenAllocationDistributed = true;
}
/**
* @dev Transfers White Rabbit tokens to the team based on the platform allocation
*
* Requirements:
*
* - All Episodes finished
* - Voting completed
*/
function withdrawPlatformReserveTokens() external onlyOwner {
require(episodes.length == _numberOfEpisodes, "Show not ended");
require(
!votingEnabledForEpisode[_numberOfEpisodes],
"Last episode still voting"
);
uint256 leftOverBalance = IERC20(whiteRabbitTokenAddress).balanceOf(
address(this)
);
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, leftOverBalance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// 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/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
struct ProducerPass {
uint256 price;
uint256 episodeId;
uint256 maxSupply;
uint256 maxPerWallet;
uint256 openMintTimestamp; // unix timestamp in seconds
bytes32 merkleRoot;
}
contract WhiteRabbitProducerPass is ERC1155, ERC1155Supply, Ownable {
using Strings for uint256;
// The name of the token ("White Rabbit Producer Pass")
string public name;
// The token symbol ("WRPP")
string public symbol;
// The wallet addresses of the two artists creating the film
address payable private artistAddress1;
address payable private artistAddress2;
// The wallet addresses of the three developers managing the film
address payable private devAddress1;
address payable private devAddress2;
address payable private devAddress3;
// The royalty percentages for the artists and developers
uint256 private constant ARTIST_ROYALTY_PERCENTAGE = 60;
uint256 private constant DEV_ROYALTY_PERCENTAGE = 40;
// A mapping of the number of Producer Passes minted per episodeId per user
// userPassesMintedPerTokenId[msg.sender][episodeId] => number of minted passes
mapping(address => mapping(uint256 => uint256))
private userPassesMintedPerTokenId;
// A mapping from episodeId to its Producer Pass
mapping(uint256 => ProducerPass) private episodeToProducerPass;
// Event emitted when a Producer Pass is bought
event ProducerPassBought(
uint256 episodeId,
address indexed account,
uint256 amount
);
/**
* @dev Initializes the contract by setting the name and the token symbol
*/
constructor(string memory baseURI) ERC1155(baseURI) {
name = "White Rabbit Producer Pass";
symbol = "WRPP";
}
/**
* @dev Checks if the provided Merkle Proof is valid for the given root hash.
*/
function isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root)
internal
view
returns (bool)
{
return
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
);
}
/**
* @dev Retrieves the Producer Pass for a given episode.
*/
function getEpisodeToProducerPass(uint256 episodeId)
external
view
returns (ProducerPass memory)
{
return episodeToProducerPass[episodeId];
}
/**
* @dev Contracts the metadata URI for the Producer Pass of the given episodeId.
*
* Requirements:
*
* - The Producer Pass exists for the given episode
*/
function uri(uint256 episodeId)
public
view
override
returns (string memory)
{
require(
episodeToProducerPass[episodeId].episodeId != 0,
"Invalid episode"
);
return
string(
abi.encodePacked(
super.uri(episodeId),
episodeId.toString(),
".json"
)
);
}
/**
* Owner-only methods
*/
/**
* @dev Sets the base URI for the Producer Pass metadata.
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_setURI(baseURI);
}
/**
* @dev Sets the parameters on the Producer Pass struct for the given episode.
*/
function setProducerPass(
uint256 price,
uint256 episodeId,
uint256 maxSupply,
uint256 maxPerWallet,
uint256 openMintTimestamp,
bytes32 merkleRoot
) external onlyOwner {
episodeToProducerPass[episodeId] = ProducerPass(
price,
episodeId,
maxSupply,
maxPerWallet,
openMintTimestamp,
merkleRoot
);
}
/**
* @dev Withdraws the balance and distributes it to the artists and developers
* based on the `ARTIST_ROYALTY_PERCENTAGE` and `DEV_ROYALTY_PERCENTAGE`.
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
uint256 artistBalance = (balance * ARTIST_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerArtist = artistBalance / 2;
uint256 devBalance = (balance * DEV_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerDev = devBalance / 3;
bool success;
// Transfer artist balances
(success, ) = artistAddress1.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
(success, ) = artistAddress2.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
// Transfer dev balances
(success, ) = devAddress1.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress2.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress3.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
}
/**
* @dev Sets the royalty addresses for the two artists and three developers.
*/
function setRoyaltyAddresses(
address _a1,
address _a2,
address _d1,
address _d2,
address _d3
) external onlyOwner {
artistAddress1 = payable(_a1);
artistAddress2 = payable(_a2);
devAddress1 = payable(_d1);
devAddress2 = payable(_d2);
devAddress3 = payable(_d3);
}
/**
* @dev Creates a reserve of Producer Passes to set aside for gifting.
*
* Requirements:
*
* - There are enough Producer Passes to mint for the given episode
* - The supply for the given episode does not exceed the maxSupply of the Producer Pass
*/
function reserveProducerPassesForGifting(
uint256 episodeId,
uint256 amountEachAddress,
address[] calldata addresses
) public onlyOwner {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(amountEachAddress > 0, "Amount cannot be 0");
require(totalSupply(episodeId) < pass.maxSupply, "No passes to mint");
require(
totalSupply(episodeId) + amountEachAddress * addresses.length <=
pass.maxSupply,
"Cannot mint that many"
);
require(addresses.length > 0, "Need addresses");
for (uint256 i = 0; i < addresses.length; i++) {
address add = addresses[i];
_mint(add, episodeId, amountEachAddress, "");
}
}
/**
* @dev Mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - The current time is within the minting window for the given episode
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function mintProducerPass(uint256 episodeId, uint256 amount)
external
payable
{
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
block.timestamp >= pass.openMintTimestamp,
"Mint is not available"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev For those on with early access (on the whitelist),
* mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - Provides a valid Merkle proof, indicating the user is on the whitelist
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function earlyMintProducerPass(
uint256 episodeId,
uint256 amount,
bytes32[] calldata merkleProof
) external payable {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
isValidMerkleProof(merkleProof, pass.merkleRoot),
"Not authorized to mint"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev Retrieves the number of Producer Passes a user has minted by episodeId.
*/
function userPassesMintedByEpisodeId(uint256 episodeId)
external
view
returns (uint256)
{
return userPassesMintedPerTokenId[msg.sender][episodeId];
}
/**
* @dev Boilerplate override for `_beforeTokenTransfer`
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// 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/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
} | Sets the White Rabbit (WRAB) token distrubution for producers. This distribution is broken into 3 categories: - Base allocation (every Producer Pass gets the same) - Early staking bonus (bonding curve distribution where earlier stakers are rewarded more) - Winning bonus (extra pot split among winning voters) Requirements: - The allocation percentages do not exceed 100%/ | function setProducerPassWhiteRabbitTokensAllocationParameters(
uint256 earlyStakingBonus,
uint256 winningVoteBonus
) external onlyOwner {
require(
(earlyStakingBonus + winningVoteBonus) <= 100,
"Total percentage exceeds 100"
);
uint256 basePercentage = 100 - earlyStakingBonus - winningVoteBonus;
producerPassTokenBaseAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * basePercentage) /
100;
producerPassTokenEarlyStakingBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * earlyStakingBonus) /
100;
producerPassTokenWinningBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * winningVoteBonus) /
100;
}
| 1,528,207 |
/**
*Submitted for verification at arbiscan.io on 2021-11-10
*/
/**
*Submitted for verification at arbiscan.io on 2021-10-18
*/
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.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;
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
pragma solidity 0.7.6;
interface IVault {
function deposit(
uint256,
uint256,
address
) external returns (uint256);
function withdraw(
uint256,
address,
address
) external returns (uint256, uint256);
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external;
function getTotalAmounts() external view returns (uint256, uint256);
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Rebalance(
int24 tick,
uint256 totalAmount0,
uint256 totalAmount1,
uint256 feeAmount0,
uint256 feeAmount1,
uint256 totalSupply
);
}
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 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;
// 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++;
}
}
}
pragma solidity >=0.5.0;
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
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;
}
}
pragma solidity >=0.6.0 <0.8.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 {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}.
*/
abstract 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_) {
_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 { }
}
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");
}
}
}
pragma solidity >=0.5.0;
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
/**
* @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;
}
}
pragma solidity 0.7.6;
// @title HyperLiquidrium
// @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3
// which allows for arbitrary liquidity provision: one-sided, lop-sided, and
// balanced
contract HyperLiquidrium is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool; // pool is not immutable as we read its value in the constructor
IERC20 public immutable token0;
IERC20 public immutable token1;
uint24 public immutable fee;
int24 public immutable tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
mapping(address=>bool) public list;
bool public whitelisted;
uint256 constant public PRECISION = 1e36;
event NewMaxSupply(uint256 newSupply);
event TokensDepositMax(uint256 token0Max, uint256 token1Max);
// @param _pool Uniswap V3 pool for which liquidity is managed
// @param _owner Owner of the HyperLiquidrium
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20(name, symbol) {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
maxTotalSupply = 0; // no cap
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
whitelisted = false;
}
// @param deposit0 Amount of token0 transfered from sender to HyperLiquidrium
// @param deposit1 Amount of token0 transfered from sender to HyperLiquidrium
// @param to Address to which liquidity tokens are minted
// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override nonReentrant returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 < deposit0Max && deposit1 < deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
if(whitelisted) {
require(list[to], "must be on the list");
}
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
}
_mint(to, shares);
emit Deposit(msg.sender, to, shares, deposit0, deposit1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
// @param shares Number of liquidity tokens to redeem as pool assets
// @param to Address to which redeemed pool assets are sent
// @param from Address from which liquidity tokens are sent
// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false);
// Push tokens proportional to unused balances
uint256 totalSupply = totalSupply();
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply);
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply);
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens");
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
// @param _baseLower The lower tick of the base position
// @param _baseUpper The upper tick of the base position
// @param _limitLower The lower tick of the limit position
// @param _limitUpper The upper tick of the limit position
// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
// @param swapQuantity Quantity of tokens to swap; if quantity is positive,
// `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity`
// token1 is swaped for token0
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override nonReentrant onlyOwner {
require(_baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0,
"base position invalid");
require(_limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0,
"limit position invalid");
require(feeRecipient == 0x7652E278A46007FDe8F10a64D0380275a76f1d8B, "Liquidrium: invalid fee address");
// update fees
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
// transfer 60% of fees for liquidrium buybacks
if(fees0 > 0) token0.safeTransfer(feeRecipient, fees0.mul(12).div(20));
if(fees1 > 0) token1.safeTransfer(feeRecipient, fees1.mul(12).div(20));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
// swap tokens if required
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
// swap tokens for X tokens manually, without changing the position
// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
// @param swapQuantity Quantity of tokens to swap; if quantity is positive,
// `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity`
// token1 is swaped for token0
function swapRebalance(
address feeRecipient,
int256 swapQuantity
) external nonReentrant {
require(feeRecipient == 0x7652E278A46007FDe8F10a64D0380275a76f1d8B, "Liquidrium: invalid fee address");
require(msg.sender == 0x2Ff58570D32E8E8B4EDeCc2c67BD3DC3EE2faC7C, "Liquidrium: wrong address");
// update fees
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
// transfer 60% of fees for liquidrium buybacks
if(fees0 > 0) token0.safeTransfer(feeRecipient, fees0.mul(12).div(20));
if(fees1 > 0) token1.safeTransfer(feeRecipient, fees1.mul(12).div(20));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
// swap tokens if required
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position,,) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool), "not pool");
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool), "not pool");
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
} else {
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
} else if (amount1Delta > 0) {
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
} else {
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
// @return total0 Quantity of token0 in both positions and unused in the HyperLiquidrium
// @return total1 Quantity of token1 in both positions and unused in the HyperLiquidrium
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
// @return liquidity Amount of total liquidity in the base position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the base position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the base position
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
// @return liquidity Amount of total liquidity in the limit position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the limit position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the limit position
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) public view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) public view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
// @return tick Uniswap pool's current price tick
function currentTick() public view returns (int24 tick) {
int24 _tick = getTwap();
return _tick;
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) {
uint32 _twapDuration = 60; // 60 seconds
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
// @param _maxTotalSupply The maximum liquidity token supply the contract allows
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
emit NewMaxSupply(_maxTotalSupply);
}
// @param _deposit0Max The maximum amount of token0 allowed in a deposit
// @param _deposit1Max The maximum amount of token1 allowed in a deposit
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
emit TokensDepositMax(_deposit0Max, _deposit1Max);
}
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
function toggleWhitelist() external onlyOwner {
whitelisted = whitelisted ? false : true;
}
function transferOwnership(address newOwner) external onlyOwner {
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
} | _deposit0Max The maximum amount of token0 allowed in a deposit _deposit1Max The maximum amount of token1 allowed in a deposit | function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
emit TokensDepositMax(_deposit0Max, _deposit1Max);
}
| 1,455,451 |
./full_match/137/0xe2fd8eb78dD4802E58812Af5b3eF62A420bA596d/sources/contracts/Martians.sol | publicupdate cost if the msgSender has a free giveaway allowance subtract mint qty from giveAway allowance | function _iterateMint(uint8 subCollection, uint8 mintQty) internal {
checkPaused();
checkMintQty(mintQty, maxMintQty);
uint256 _afterMintSupply = totalSupply() + mintQty;
checkMaxSupply(_afterMintSupply);
checkSupplyAndReserved(subCollection, mintQty);
if(mintQty <= giveAwayAllowance[subCollection][_msgSender()]){
giveAwayAllowance[subCollection][_msgSender()] = mintQty;
checkTxCost(msg.value, (cost[subCollection] * mintQty));
}
for (uint256 i; i < mintQty; i++) {
_mintTx(subCollection);
}
}
| 4,665,486 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() 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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// // Auction wrapper functions
// Auction wrapper functions
/// @title SEKRETOOOO
contract GeneScienceInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneScience() public pure returns (bool);
/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
contract VariationInterface {
function isVariation() public pure returns(bool);
function createVariation(uint256 _gene, uint256 _totalSupply) public returns (uint8);
function registerVariation(uint256 _dogId, address _owner) public;
}
contract LotteryInterface {
function isLottery() public pure returns (bool);
function checkLottery(uint256 genes) public pure returns (uint8 lotclass);
function registerLottery(uint256 _dogId) public payable returns (uint8);
function getCLottery()
public
view
returns (
uint8[7] luckyGenes1,
uint256 totalAmount1,
uint256 openBlock1,
bool isReward1,
uint256 term1,
uint8 currentGenes1,
uint256 tSupply,
uint256 sPoolAmount1,
uint256[] reward1
);
}
/// @title A facet of KittyCore that manages special access privileges.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogAccessControl {
// This facet controls access control for Cryptodogs. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the KittyCore constructor.
//
// - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts.
//
// - The COO: The COO can release gen0 dogs to auction, and mint promo cats.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for Cryptodogs. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogBase is DogAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
/// includes any time a cat is created through the giveBirth method, but it is also called
/// when a new gen0 cat is created.
event Birth(address owner, uint256 dogId, uint256 matronId, uint256 sireId, uint256 genes, uint16 generation, uint8 variation, uint256 gen0, uint256 birthTime, uint256 income, uint16 cooldownIndex);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Dog struct. Every cat in Cryptodogs is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Dog {
// The Dog's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A cat's genes never change.
uint256 genes;
// The timestamp from the block when this cat came into existence.
uint256 birthTime;
// The minimum timestamp after which this cat can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this Dog, set to 0 for gen0 cats.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion cats. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire cat for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a cat
// is pregnant. Used to retrieve the genetic material for the new
// kitten when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Dog. This starts at zero
// for gen0 cats, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this cat is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this cat. Cats minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other cats is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
//zhangyong
//变异系数
uint8 variation;
//zhangyong
//0代狗祖先
uint256 gen0;
}
/*** CONSTANTS ***/
/// @dev A lookup table indicating the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a cat
/// is bred, encouraging owners not to just keep breeding the same cat over
/// and over again. Caps out at one week (a cat can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(24 hours),
uint32(2 days),
uint32(3 days),
uint32(5 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Dog struct for all dogs in existence. The ID
/// of each cat is actually an index into this array. Note that ID 0 is a negacat,
/// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, cat ID 0 is invalid... ;-)
Dog[] dogs;
/// @dev A mapping from cat IDs to the address that owns them. All cats have
/// some valid owner address, even gen0 cats are created with a non-zero owner.
mapping (uint256 => address) dogIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from KittyIDs to an address that has been approved to call
/// transferFrom(). Each Dog can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public dogIndexToApproved;
/// @dev A mapping from KittyIDs to an address that has been approved to use
/// this Dog for siring via breedWith(). Each Dog can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of dogs. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
uint256 public autoBirthFee = 5000 szabo;
//zhangyong
//0代狗获取的繁殖收益
uint256 public gen0Profit = 500 szabo;
//zhangyong
//0代狗获取繁殖收益的系数,可以动态调整,取值范围0到100
function setGen0Profit(uint256 _value) public onlyCOO{
uint256 ration = _value * 100 / autoBirthFee;
require(ration > 0);
require(_value <= 100);
gen0Profit = _value;
}
/// @dev Assigns ownership of a specific Dog to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of kittens is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
dogIndexToOwner[_tokenId] = _to;
// When creating new kittens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the kitten is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete dogIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new Dog and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The Dog ID of the matron of this cat (zero for gen0)
/// @param _sireId The Dog ID of the sire of this cat (zero for gen0)
/// @param _generation The generation number of this cat, must be computed by caller.
/// @param _genes The Dog's genetic code.
/// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0)
//zhangyong
//增加变异系数与0代狗祖先作为参数
function _createDog(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint8 _variation,
uint256 _gen0,
bool _isGen0Siring
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createDog() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New Dog starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Dog memory _dog = Dog({
genes: _genes,
birthTime: block.number,
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation),
variation : uint8(_variation),
gen0 : _gen0
});
uint256 newDogId = dogs.push(_dog) - 1;
// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
// require(newDogId == uint256(uint32(newDogId)));
require(newDogId < 23887872);
// emit the birth event
Birth(
_owner,
newDogId,
uint256(_dog.matronId),
uint256(_dog.sireId),
_dog.genes,
uint16(_generation),
_variation,
_gen0,
block.number,
_isGen0Siring ? 0 : gen0Profit,
cooldownIndex
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newDogId);
return newDogId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the dogs,
/// it has one function that will return the data as bytes.
// contract ERC721Metadata {
// /// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
// function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
// if (_tokenId == 1) {
// buffer[0] = "Hello World! :D";
// count = 15;
// } else if (_tokenId == 2) {
// buffer[0] = "I would definitely choose a medi";
// buffer[1] = "um length string.";
// count = 49;
// } else if (_tokenId == 3) {
// buffer[0] = "Lorem ipsum dolor sit amet, mi e";
// buffer[1] = "st accumsan dapibus augue lorem,";
// buffer[2] = " tristique vestibulum id, libero";
// buffer[3] = " suscipit varius sapien aliquam.";
// count = 128;
// }
// }
// }
/// @title The facet of the Cryptodogs core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogOwnership is DogBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "HelloDog";
string public constant symbol = "HD";
// The contract that will return Dog metadata
// ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)"));
// bytes4(keccak256("tokensOfOwner(address)")) ^
// bytes4(keccak256("tokenMetadata(uint256,string)"));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
// function setMetadataAddress(address _contractAddress) public onlyCEO {
// erc721Metadata = ERC721Metadata(_contractAddress);
// }
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Dog.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return dogIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Dog.
/// @param _claimant the address we are confirming kitten is approved for.
/// @param _tokenId kitten id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return dogIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting dogs on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
dogIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of dogs owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Dog to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Cryptodogs specifically) or your Dog may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Dog to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any dogs (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of dogs
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// You can only send your own cat.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Dog via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Dog that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Dog owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Dog to be transfered.
/// @param _to The address that should take ownership of the Dog. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Dog to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any dogs (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of dogs currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return dogs.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Dog.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = dogIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Dog IDs assigned to an address.
/// @param _owner The owner whose dogs we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Dog array looking for cats belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
// function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
// uint256 tokenCount = balanceOf(_owner);
// if (tokenCount == 0) {
// // Return an empty array
// return new uint256[](0);
// } else {
// uint256[] memory result = new uint256[](tokenCount);
// uint256 totalCats = totalSupply();
// uint256 resultIndex = 0;
// // We count on the fact that all cats have IDs starting at 1 and increasing
// // sequentially up to the totalCat count.
// uint256 catId;
// for (catId = 1; catId <= totalCats; catId++) {
// if (dogIndexToOwner[catId] == _owner) {
// result[resultIndex] = catId;
// resultIndex++;
// }
// }
// return result;
// }
// }
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
// function _memcpy(uint _dest, uint _src, uint _len) private view {
// // Copy word-length chunks while possible
// for(; _len >= 32; _len -= 32) {
// assembly {
// mstore(_dest, mload(_src))
// }
// _dest += 32;
// _src += 32;
// }
// // Copy remaining bytes
// 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))
// }
// }
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
// function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
// var outputString = new string(_stringLength);
// uint256 outputPtr;
// uint256 bytesPtr;
// assembly {
// outputPtr := add(outputString, 32)
// bytesPtr := _rawBytes
// }
// _memcpy(outputPtr, bytesPtr, _stringLength);
// return outputString;
// }
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Dog whose metadata should be returned.
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
// require(erc721Metadata != address(0));
// bytes32[4] memory buffer;
// uint256 count;
// (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
// return _toString(buffer, count);
// }
}
/// @title A facet of KittyCore that manages Dog siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogBreeding is DogOwnership {
/// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 matronCooldownIndex, uint256 sireCooldownIndex);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
// uint256 public autoBirthFee = 2 finney;
// Keeps track of number of pregnant dogs.
uint256 public pregnantDogs;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneScienceInterface public geneScience;
VariationInterface public variation;
LotteryInterface public lottery;
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
/// @dev Checks that a given kitten is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(Dog _dog) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_dog.siringWithId == 0) && (_dog.cooldownEndBlock <= uint64(block.number));
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = dogIndexToOwner[_matronId];
address sireOwner = dogIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given Dog, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _dog A reference to the Dog in storage which needs its timer started.
function _triggerCooldown(Dog storage _dog) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_dog.cooldownEndBlock = uint64((cooldowns[_dog.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_dog.cooldownIndex < 13) {
_dog.cooldownIndex += 1;
}
}
/// @notice Grants approval to another user to sire with one of your dogs.
/// @param _addr The address that will be able to sire with your Dog. Set to
/// address(0) to clear all siring approvals for this Dog.
/// @param _sireId A Dog that you own that _addr will now be able to sire with.
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
require(val > 0);
autoBirthFee = val;
}
/// @dev Checks to see if a given Dog is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(Dog _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _dogId reference the id of the kitten, any user can inquire about it
function isReadyToBreed(uint256 _dogId)
public
view
returns (bool)
{
//zhangyong
//创世狗有两只
require(_dogId > 1);
Dog storage dog = dogs[_dogId];
return _isReadyToBreed(dog);
}
/// @dev Checks whether a Dog is currently pregnant.
/// @param _dogId reference the id of the kitten, any user can inquire about it
function isPregnant(uint256 _dogId)
public
view
returns (bool)
{
// A Dog is pregnant if and only if this field is set
return dogs[_dogId].siringWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Dog struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Dog struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Dog storage _matron,
uint256 _matronId,
Dog storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
// A Dog can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// dogs can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either cat is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// dogs can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Dog storage matron = dogs[_matronId];
Dog storage sire = dogs[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
// @notice Checks to see if two cats can breed together, including checks for
// ownership and siring approvals. Does NOT check that both cats are ready for
// breeding (i.e. breedWith could still fail until the cooldowns are finished).
// TODO: Shouldn't this check pregnancy and cooldowns?!?
// @param _matronId The ID of the proposed matron.
// @param _sireId The ID of the proposed sire.
// function canBreedWith(uint256 _matronId, uint256 _sireId)
// external
// view
// returns(bool)
// {
// require(_matronId > 1);
// require(_sireId > 1);
// Dog storage matron = dogs[_matronId];
// Dog storage sire = dogs[_sireId];
// return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
// _isSiringPermitted(_sireId, _matronId);
// }
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
//zhangyong
//创世狗不能繁殖
require(_matronId > 1);
require(_sireId > 1);
// Grab a reference to the dogs from storage.
Dog storage sire = dogs[_sireId];
Dog storage matron = dogs[_matronId];
//zhangyong
//变异狗不能繁殖
require(sire.variation == 0);
require(matron.variation == 0);
if (matron.generation > 0) {
var(,,openBlock,,,,,,) = lottery.getCLottery();
if (matron.birthTime < openBlock) {
require(lottery.checkLottery(matron.genes) == 100);
}
}
// Mark the matron as pregnant, keeping track of who the sire is.
matron.siringWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// Every time a Dog gets pregnant, counter is incremented.
pregnantDogs++;
//zhangyong
//只能由系统接生,接生费转给公司作为开发费用
cfoAddress.transfer(autoBirthFee);
//zhangyong
//如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同
if (matron.generation > 0) {
dogIndexToOwner[matron.gen0].transfer(gen0Profit);
}
// Emit the pregnancy event.
Pregnant(dogIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock, sire.cooldownEndBlock, matron.cooldownIndex, sire.cooldownIndex);
}
/// @notice Breed a Dog you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your cat pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the Dog acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the Dog acting as sire (will begin its siring cooldown if successful)
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// zhangyong
// 如果不是0代狗繁殖,则多收0代狗的繁殖收益
uint256 totalFee = autoBirthFee;
Dog storage matron = dogs[_matronId];
if (matron.generation > 0) {
totalFee += gen0Profit;
}
// Checks for payment.
require(msg.value >= totalFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
// Neither sire nor matron are allowed to be on auction during a normal
// breeding operation, but we don't need to check that explicitly.
// For matron: The caller of this function can't be the owner of the matron
// because the owner of a Dog on auction is the auction house, and the
// auction house will never call breedWith().
// For sire: Similarly, a sire on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any oustanding
// siring approval.
// Thus we don't need to spend gas explicitly checking to see if either cat
// is on auction.
// Check that matron and sire are both owned by caller, or that the sire
// has given siring permission to caller (i.e. matron's owner).
// Will fail for _sireId = 0
require(_isSiringPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
// Dog storage matron = dogs[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(matron));
// Grab a reference to the potential sire
Dog storage sire = dogs[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(sire));
// Test that these cats are a valid mating pair.
require(_isValidMatingPair(matron, _matronId, sire, _sireId));
// All checks passed, Dog gets pregnant!
_breedWith(_matronId, _sireId);
// zhangyong
// 多余的费用返还给用户
uint256 breedExcess = msg.value - totalFee;
if (breedExcess > 0) {
msg.sender.transfer(breedExcess);
}
}
/// @notice Have a pregnant Dog give birth!
/// @param _matronId A Dog ready to give birth.
/// @return The Dog ID of the new kitten.
/// @dev Looks at a given Dog and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new kitten. The new Dog is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new kitten will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new kitten always goes to the mother's owner.
//zhangyong
//只能由系统接生,接生费转给公司作为开发费用,同时避免其他人帮助接生后,后台不知如何处理
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns(uint256)
{
// Grab a reference to the matron in storage.
Dog storage matron = dogs[_matronId];
// Check that the matron is a valid cat.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.siringWithId;
Dog storage sire = dogs[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
//zhangyong
//如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同
uint256 gen0 = matron.generation == 0 ? _matronId : matron.gen0;
// Call the sooper-sekret gene mixing operation.
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// Make the new kitten!
address owner = dogIndexToOwner[_matronId];
uint8 _variation = variation.createVariation(childGenes, dogs.length);
bool isGen0Siring = matron.generation == 0;
uint256 kittenId = _createDog(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner, _variation, gen0, isGen0Siring);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.siringWithId;
// Every time a Dog gives birth counter is decremented.
pregnantDogs--;
// Send the balance fee to the person who made birth happen.
if(_variation != 0){
variation.registerVariation(kittenId, owner);
_transfer(owner, address(variation), kittenId);
}
// return the new kitten's ID
return kittenId;
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount, address _to)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
uint256 auctioneerCut = computeCut(price);
//zhangyong
//两只创世狗每次交易需要收取10%的手续费
//创世狗无法繁殖,所以只有创世狗交易才会进入到这个方法
uint256 fee = 0;
if (_tokenId == 0 || _tokenId == 1) {
fee = price / 5;
}
require((_bidAmount + auctioneerCut + fee) >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 sellerProceeds = price - auctioneerCut - fee;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
// zhangyong
// _bidAmount在进入这个方法之前已经扣掉了fee,所以买者需要加上这笔费用才等于开始出价
// uint256 bidExcess = _bidAmount + fee - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
// zhangyong
// msg.sender是主合约地址,并不是出价人的地址
// msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, _to);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function computeCut(uint256 _price) public view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
// bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)"));
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
nftAddress.transfer(address(this).balance);
}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of item (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at end of auction.
// @param _duration - Length of time to move between starting
// price and ending price (in seconds).
// @param _seller - Seller, if not the message sender
// function createAuction(
// uint256 _tokenId,
// uint256 _startingPrice,
// uint256 _endingPrice,
// uint256 _duration,
// address _seller
// )
// external
// whenNotPaused
// {
// // Sanity check that no inputs overflow how many bits we've allocated
// // to store them in the auction struct.
// require(_startingPrice == uint256(uint128(_startingPrice)));
// require(_endingPrice == uint256(uint128(_endingPrice)));
// require(_duration == uint256(uint64(_duration)));
// require(_owns(msg.sender, _tokenId));
// _escrow(msg.sender, _tokenId);
// Auction memory auction = Auction(
// _seller,
// uint128(_startingPrice),
// uint128(_endingPrice),
// uint64(_duration),
// uint64(now)
// );
// _addAuction(_tokenId, auction);
// }
// @dev Bids on an open auction, completing the auction and transferring
// ownership of the NFT if enough Ether is supplied.
// @param _tokenId - ID of token to bid on.
// function bid(uint256 _tokenId)
// external
// payable
// whenNotPaused
// {
// // _bid will throw if the bid or funds transfer fails
// _bid(_tokenId, msg.value);
// _transfer(msg.sender, _tokenId);
// }
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
// zhangyong
// 普通用户无法下架创世狗
require(_tokenId > 1);
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
// Delegate constructor
function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be KittyCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for siring. Requires the sender
/// is the KittyCore contract because all bid methods
/// should be wrapped. Also returns the Dog to the
/// seller rather than the winner.
function bid(uint256 _tokenId, address _to)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value, _to);
// We transfer the Dog back to the seller, the winner will get
// the offspring
_transfer(seller, _tokenId);
}
}
/// @title Clock auction modified for sale of dogs
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 Dog sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId, address _to)
external
payable
{
//zhangyong
//只能由主合约调用出价竞购,因为要判断当期中奖了的狗无法买卖
require(msg.sender == address(nonFungibleContract));
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
// zhangyong
// 自己不能买自己卖的同一只狗
require(seller != _to);
uint256 price = _bid(_tokenId, msg.value, _to);
//zhangyong
//当狗被拍卖后,主人变成拍卖合约,主合约并不是狗的购买人,需要额外传入
_transfer(_to, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Handles creating auctions for sale and siring of dogs.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract DogAuction is DogBreeding {
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// @notice The auction contract variables are defined in KittyBase to allow
// us to refer to them in KittyOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of dogs.
// `siringAuction` refers to the auction for siring rights of dogs.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Put a Dog up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _dogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Dog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId));
// Ensure the Dog is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Dog IS allowed to be in a cooldown.
require(!isPregnant(_dogId));
_approve(_dogId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Dog.
saleAuction.createAuction(
_dogId,
_startingPrice,
_endingPrice,
_duration,
dogIndexToOwner[_dogId]
);
}
/// @dev Put a Dog up for auction to be sire.
/// Performs checks to ensure the Dog can be sired, then
/// delegates to reverse auction.
function createSiringAuction(
uint256 _dogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
//zhangyong
Dog storage dog = dogs[_dogId];
//变异狗不能繁殖
require(dog.variation == 0);
// Auction contract checks input sizes
// If Dog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _dogId));
require(isReadyToBreed(_dogId));
_approve(_dogId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Dog.
siringAuction.createAuction(
_dogId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
// zhangyong
// 如果不是0代狗繁殖,则多收0代狗的繁殖收益
uint256 totalFee = currentPrice + autoBirthFee;
Dog storage matron = dogs[_matronId];
if (matron.generation > 0) {
totalFee += gen0Profit;
}
require(msg.value >= totalFee);
uint256 auctioneerCut = saleAuction.computeCut(currentPrice);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(currentPrice - auctioneerCut)(_sireId, msg.sender);
_breedWith(uint32(_matronId), uint32(_sireId));
// zhangyong
// 额外的钱返还给用户
uint256 bidExcess = msg.value - totalFee;
if (bidExcess > 0) {
msg.sender.transfer(bidExcess);
}
}
// zhangyong
// 创世狗交易需要收取10%的手续费给CFO
// 所有交易都要收取3.75%的手续费给买卖合约
function bidOnSaleAuction(
uint256 _dogId
)
external
payable
whenNotPaused
{
Dog storage dog = dogs[_dogId];
//中奖的狗无法交易
if (dog.generation > 0) {
var(,,openBlock,,,,,,) = lottery.getCLottery();
if (dog.birthTime < openBlock) {
require(lottery.checkLottery(dog.genes) == 100);
}
}
//交易成功之后,买卖合约会被删除,无法获取到当前价格
uint256 currentPrice = saleAuction.getCurrentPrice(_dogId);
require(msg.value >= currentPrice);
//创世狗交易需要收取10%的手续费
bool isCreationKitty = _dogId == 0 || _dogId == 1;
uint256 fee = 0;
if (isCreationKitty) {
fee = currentPrice / 5;
}
uint256 auctioneerCut = saleAuction.computeCut(currentPrice);
saleAuction.bid.value(currentPrice - (auctioneerCut + fee))(_dogId, msg.sender);
// 创世狗被交易之后,下次的价格为当前成交价的2倍
if (isCreationKitty) {
//转账到主合约进行,因为买卖合约访问不了cfoAddress
cfoAddress.transfer(fee);
uint256 nextPrice = uint256(uint128(2 * currentPrice));
if (nextPrice < currentPrice) {
nextPrice = currentPrice;
}
_approve(_dogId, saleAuction);
saleAuction.createAuction(
_dogId,
nextPrice,
nextPrice,
GEN0_AUCTION_DURATION,
msg.sender);
}
uint256 bidExcess = msg.value - currentPrice;
if (bidExcess > 0) {
msg.sender.transfer(bidExcess);
}
}
// @dev Transfers the balance of the sale auction contract
// to the KittyCore contract. We use two-step withdrawal to
// prevent two transfer calls in the auction bid function.
// function withdrawAuctionBalances() external onlyCLevel {
// saleAuction.withdrawBalance();
// siringAuction.withdrawBalance();
// }
}
/// @title all functions related to creating kittens
contract DogMinting is DogAuction {
// Limits the number of cats the contract owner can ever create.
// uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 40000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 200 finney;
// uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// Counts the number of cats the contract owner has created.
// uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
// @dev we can create promo kittens, up to a limit. Only callable by COO
// @param _genes the encoded genes of the kitten to be created, any value is accepted
// @param _owner the future owner of the created kittens. Default to contract COO
// function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
// address kittyOwner = _owner;
// if (kittyOwner == address(0)) {
// kittyOwner = cooAddress;
// }
// require(promoCreatedCount < PROMO_CREATION_LIMIT);
// promoCreatedCount++;
// //zhangyong
// //增加变异系数与0代狗祖先作为参数
// _createDog(0, 0, 0, _genes, kittyOwner, 0, 0, false);
// }
// @dev Creates a new gen0 Dog with the given genes
function createGen0Dog(uint256 _genes) external onlyCLevel returns(uint256) {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
//zhangyong
//增加变异系数与0代狗祖先作为参数
uint256 dogId = _createDog(0, 0, 0, _genes, address(this), 0, 0, false);
_approve(dogId, msg.sender);
gen0CreatedCount++;
return dogId;
}
/// @dev creates an auction for it.
// function createGen0Auction(uint256 _dogId) external onlyCOO {
// require(_owns(address(this), _dogId));
// _approve(_dogId, saleAuction);
// //zhangyong
// //0代狗的价格随时间递减到最低价,起始价与前5只价格相关
// uint256 price = _computeNextGen0Price();
// saleAuction.createAuction(
// _dogId,
// price,
// price,
// GEN0_AUCTION_DURATION,
// address(this)
// );
// }
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function computeNextGen0Price() public view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
/// @title Cryptodogs: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main Cryptodogs contract, keeps track of kittens so they don't wander around and get lost.
contract DogCore is DogMinting {
// This is the main Cryptodogs contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// Dog ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - KittyBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - KittyAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - KittyOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - KittyBreeding: This file contains the methods necessary to breed cats together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats.
// We can make up to 5000 "promo" cats that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main Cryptodogs smart contract instance.
function DogCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the mythical kitten 0 - so we don't have generation-0 parent issues
//zhangyong
//增加变异系数与0代狗祖先作为参数
_createDog(0, 0, 0, uint256(0), address(this), 0, 0, false);
_approve(0, cooAddress);
_createDog(0, 0, 0, uint256(0), address(this), 0, 0, false);
_approve(1, cooAddress);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction) ||
msg.sender == ceoAddress
);
}
/// @notice Returns all the relevant information about a specific Dog.
/// @param _id The ID of the Dog of interest.
function getDog(uint256 _id)
external
view
returns (
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes,
uint8 variation,
uint256 gen0
) {
Dog storage dog = dogs[_id];
// if this variable is 0 then it's not gestating
cooldownIndex = uint256(dog.cooldownIndex);
nextActionAt = uint256(dog.cooldownEndBlock);
siringWithId = uint256(dog.siringWithId);
birthTime = uint256(dog.birthTime);
matronId = uint256(dog.matronId);
sireId = uint256(dog.sireId);
generation = uint256(dog.generation);
genes = uint256(dog.genes);
variation = uint8(dog.variation);
gen0 = uint256(dog.gen0);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(lottery != address(0));
require(variation != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
function setLotteryAddress(address _address) external onlyCEO {
LotteryInterface candidateContract = LotteryInterface(_address);
require(candidateContract.isLottery());
lottery = candidateContract;
}
function setVariationAddress(address _address) external onlyCEO {
VariationInterface candidateContract = VariationInterface(_address);
require(candidateContract.isVariation());
variation = candidateContract;
}
function registerLottery(uint256 _dogId) external returns (uint8) {
require(_owns(msg.sender, _dogId));
require(lottery.registerLottery(_dogId) == 0);
_transfer(msg.sender, address(lottery), _dogId);
}
function sendMoney(address _to, uint256 _money) external {
require(msg.sender == address(lottery) || msg.sender == address(variation));
require(address(this).balance >= _money);
_to.transfer(_money);
}
} | Internal check to see if a given sire and matron are a valid mating pair. DOES NOT check ownership permissions (that is up to the caller). _matron A reference to the Dog struct of the potential matron. _matronId The matron&39;s ID. _sire A reference to the Dog struct of the potential sire. _sireId The sire&39;s ID A Dog can&39;t breed with itself! dogs can&39;t breed with their parents. We can short circuit the sibling check (below) if either cat is gen zero (has a matron ID of zero). dogs can&39;t breed with full or half siblings. | function _isValidMatingPair(
Dog storage _matron,
uint256 _matronId,
Dog storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
if (_matronId == _sireId) {
return false;
}
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
}
| 2,460,329 |
./full_match/11155111/0xA7a7a82597063CF4e3AC51bF601Ce75D12126C45/sources/contracts/Safe.sol | Returns the domain separator for this contract, as defined in the EIP-712 standard. return bytes32 The domain separator hash./ solhint-disable no-inline-assembly / @solidity memory-safe-assembly | function domainSeparator() public view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this));
}
| 3,832,815 |
./full_match/3/0xd001433ea82bCd77ff66706723c37bb733bD609d/sources/browser/Untitled.sol | Cannot enforce "AllowedRoles":["Buyer"] because Role information is unavailable | function MakeOffer(address inspector, address appraiser, uint256 offerPrice) public
{
if (inspector == 0x0000000000000000000000000000000000000000 || appraiser == 0x0000000000000000000000000000000000000000 || offerPrice == 0)
{
revert();
}
if (State != StateType.Active)
{
revert();
}
{
revert();
}
InstanceBuyer = msg.sender;
InstanceInspector = inspector;
InstanceAppraiser = appraiser;
OfferPrice = offerPrice;
State = StateType.OfferPlaced;
}
| 8,175,117 |
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "hardhat/console.sol";
//Need to create NFT's
//Need to be able to sell NFT to an address
//Need to be able to buy an NFT from an address
//Need to be able to randomly generate a winner in raffle
contract Raffle is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
//Needs to be updated with oracle for random number generation
uint256 private seed;
mapping(uint => address) public nftAddress;
function inspectOwners() view public{
for(uint i = 0; i < _tokenIds.current(); i++){
console.log("Inspecting owners, %s", nftAddress[i]);
}
}
//Array of NFT ID's with a map to owner
// Function to receive Ether. msg.data must be empty
receive() external payable {}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
// We need to pass the name of our NFTs token and its symbol.
constructor() ERC721 ("RaffleNFT", "RAFFLE") payable {
}
//Make an NFT
function makeNFT() public {
//TODO Check to make sure that we aren't out of bounds for how many NFT's we have
//When using safemint, If the target address is a contract, it must implement onERC721Received
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
//For testing, use a hosting website, for prod would need to use IPFS
_setTokenURI(newItemId, "data:application/json;base64,ewogICAgIm5hbWUiOiAiRXBpY0xvcmRIYW1idXJnZXIiLAogICAgImRlc2NyaXB0aW9uIjogIkFuIE5GVCBmcm9tIHRoZSBoaWdobHkgYWNjbGFpbWVkIHNxdWFyZSBjb2xsZWN0aW9uIiwKICAgICJpbWFnZSI6ICJkYXRhOmltYWdlL3N2Zyt4bWw7YmFzZTY0LFBITjJaeUI0Yld4dWN6MGlhSFIwY0RvdkwzZDNkeTUzTXk1dmNtY3ZNakF3TUM5emRtY2lJSEJ5WlhObGNuWmxRWE53WldOMFVtRjBhVzg5SW5oTmFXNVpUV2x1SUcxbFpYUWlJSFpwWlhkQ2IzZzlJakFnTUNBek5UQWdNelV3SWo0TkNpQWdJQ0E4YzNSNWJHVStMbUpoYzJVZ2V5Qm1hV3hzT2lCM2FHbDBaVHNnWm05dWRDMW1ZVzFwYkhrNklITmxjbWxtT3lCbWIyNTBMWE5wZW1VNklERTBjSGc3SUgwOEwzTjBlV3hsUGcwS0lDQWdJRHh5WldOMElIZHBaSFJvUFNJeE1EQWxJaUJvWldsbmFIUTlJakV3TUNVaUlHWnBiR3c5SW1Kc1lXTnJJaUF2UGcwS0lDQWdJRHgwWlhoMElIZzlJalV3SlNJZ2VUMGlOVEFsSWlCamJHRnpjejBpWW1GelpTSWdaRzl0YVc1aGJuUXRZbUZ6Wld4cGJtVTlJbTFwWkdSc1pTSWdkR1Y0ZEMxaGJtTm9iM0k5SW0xcFpHUnNaU0krUlhCcFkweHZjbVJJWVcxaWRYSm5aWEk4TDNSbGVIUStEUW84TDNOMlp6ND0iCn0=");
console.log("An NFT w/ ID %s has been minted to %s", newItemId, msg.sender);
nftAddress[newItemId] = msg.sender;
console.log("nftAddresses, %s", nftAddress[newItemId]);
_tokenIds.increment();
}
//Purchase a raffle ticket back from customer
function buyBackNFT(address NFTaddress) public {
}
//Sell a raffle ticket to a customer
function sellNFT(uint256 amount, uint nftId, address buyerAddress) public{
//Receive funds
//Increment counter for how many NFT's are left
require(
amount <= address(this).balance,
"Trying to withdraw more money than they contract has."
);
(bool success, ) = (msg.sender).call{value: amount}("");
require(success, "Failed to withdraw money from contract.");
//Transfer ownership of NFT
nftAddress[nftId] = buyerAddress;
}
//Buying back an NFT
function sendViaCall(address payable _to) public payable {
// Call returns a boolean value indicating success or failure.
// This is the current recommended method to use.
(bool sent, bytes memory data) = _to.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
//TEST NFT JSON DATA
//https://jsonkeeper.com/b/OD3Z
//NOTE: NFT data should be stored as an SVG.
} | Purchase a raffle ticket back from customer | function buyBackNFT(address NFTaddress) public {
}
| 13,089,757 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/// @title JustBackgrounds
/// @author jpegmint.xyz
import "@openzeppelin/contracts/access/Ownable.sol";
import "@jpegmint/contracts/collectibles/ERC721PresetCollectible.sol";
/////////////////////////////////////////////////////////////////////////////////
// __ __ ___ __ __ //
// __ / /_ _____ / /_ / _ )___ _____/ /_____ ________ __ _____ ___/ /__ //
// / // / // (_-</ __/ / _ / _ `/ __/ '_/ _ `/ __/ _ \/ // / _ \/ _ (_-< //
// \___/\_,_/___/\__/ /____/\_,_/\__/_/\_\\_, /_/ \___/\_,_/_//_/\_,_/___/ //
// /___/ //
/////////////////////////////////////////////////////////////////////////////////
contract JustBackgrounds is ERC721PresetCollectible, Ownable {
using Strings for uint256;
/// Structs ///
struct ColorTraits {
string tokenId;
string hexCode;
string name;
string displayName;
string family;
string source;
string brightness;
string special;
}
/// Constants ///
bytes16 private constant _HEX_SYMBOLS = "0123456789ABCDEF";
bytes private constant _COLOR_NAMES = bytes("AcaciaAccedeAccessAceticAcidicAddictAdobesAffectAlice BlueAmberAmethystAntique WhiteAquaAquamarineAshAssessAssetsAssistAttestAtticsAzureBabiesBaffedBasicsBeadedBeastsBeddedBeefedBeigeBidetsBirchBisqueBlackBlanched AlmondBlueBlue VioletBoastsBobbedBobcatBodiesBoobieBossesBrassBronzeBrownBurly WoodCaddieCadet BlueCeasedCedarChartreuseCherryChocolateCicadaCoffeeCootieCopperCoralCornflower BlueCornsilkCrimsonCyanDabbedDaffedDark BlueDark CyanDark GoldenrodDark GrayDark GreenDark KhakiDark MagentaDark Olive GreenDark OrangeDark OrchidDark RedDark SalmonDark Sea GreenDark Slate BlueDark Slate GrayDark TurquoiseDark VioletDebaseDecadeDecideDeededDeep PinkDeep Sky BlueDefaceDefeatDefectDetectDetestDiamondDibbedDim GrayDiodesDissedDodger BlueDoodadDottedEddiesEffaceEffectEmeraldEstateFacadeFacetsFasciaFastedFibbedFiestaFirFire BrickFittedFloral WhiteFootedForest GreenFuchsiaGainsboroGhost WhiteGoldGoldenrodGrayGreenGreen YellowHoney DewHot PinkIndian RedIndigoIvoryJadeKhakiLavenderLavender BlushLawn GreenLemon ChiffonLight BlueLight CoralLight CyanLight Goldenrod YellowLight GrayLight GreenLight PinkLight SalmonLight Sea GreenLight Sky BlueLight Slate GrayLight Steel BlueLight YellowLimeLime GreenLinenMagentaMahoganyMapleMaroonMedium AquamarineMedium BlueMedium OrchidMedium PurpleMedium Sea GreenMedium Slate BlueMedium Spring GreenMedium TurquoiseMedium Violet RedMidnight BlueMint CreamMisty RoseMoccasinNavajo WhiteNavyOakOdessaOfficeOld LaceOliveOlive DrabOrangeOrange RedOrchidPale GoldenrodPale GreenPale TurquoisePale Violet RedPalladiumPapaya WhipPatinaPeach PuffPearlPeruPinePinkPlatinumPlumPowder BluePurplePyriteQuartzRebecca PurpleRedRedwoodRose GoldRose QuartzRosewoodRosy BrownRoyal BlueRubySaddle BrownSadistSafestSalmonSandy BrownSapphireSassedScoffsSea GreenSea ShellSeabedSecedeSeededSiennaSiestaSilverSky BlueSlate BlueSlate GraySnowSobbedSpring GreenStaticSteel BlueTabbedTacticTanTeakTealTeasedTeasesTestedThistleTictacTidbitToastsToffeeTomatoTootedTransparentTransparent?TurquoiseVioletWalnutWheatWhiteWhite SmokeYellowYellow Green");
/// Variables ///
bool private _initialized;
bytes8[] private _colorMetadata;
/// Mappings ///
mapping(uint256 => bytes8) private _tokenToColorIndex;
//================================================================================
// Constructor & Initialization
//================================================================================
/**
* @dev Constructor. Collectible preset handles most setup.
*/
constructor()
ERC721PresetCollectible("JustBackgrounds", "GRNDS", 256, 0.01 ether, 5, 10) {}
/**
* @dev Stores metadata for each token and marks as initialized.
*/
function initializeMetadata(bytes8[] memory colorMetadata) external {
require(!_initialized, "GRNDS: Metadata already initialized");
require(colorMetadata.length == _tokenMaxSupply, "GRNDS: Not enough metadata provided");
_colorMetadata = colorMetadata;
_initialized = true;
}
//================================================================================
// Access Control Wrappers
//================================================================================
function startSale() external override onlyOwner {
require(_initialized, "GRNDS: Metadata not initialized");
_unpause();
}
function pauseSale() external override onlyOwner {
_pause();
}
function reserveCollectibles() external onlyOwner {
require(_initialized, "GRNDS: Metadata not initialized");
_reserveCollectibles();
}
function withdraw() external override onlyOwner {
_withdraw();
}
//================================================================================
// Minting Functions
//================================================================================
/**
* @dev Select random color, store, and remove from unused in after-mint hook.
*/
function _afterTokenMint(address, uint256 tokenId) internal override {
_tokenToColorIndex[tokenId] = _consumeUnusedColor(tokenId);
}
/**
* @dev Selects random color from available colors.
*/
function _consumeUnusedColor(uint256 tokenId) private returns (bytes8) {
uint256 index = _reserved ? _generateRandomNum(tokenId) % _colorMetadata.length : tokenId - 1;
bytes8 color = _colorMetadata[index];
_colorMetadata[index] = _colorMetadata[_colorMetadata.length - 1];
_colorMetadata.pop();
return color;
}
/**
* @dev Generates pseudorandom number.
*/
function _generateRandomNum(uint256 seed) private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, seed)));
}
//================================================================================
// Metadata Functions
//================================================================================
/**
* @dev On-chain, dynamic generation of Background metadata and SVG.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "GRNDS: URI query for nonexistent token");
ColorTraits memory traits = _getColorTraits(tokenId);
bytes memory byteString;
byteString = abi.encodePacked(byteString, 'data:application/json;utf8,{');
byteString = abi.encodePacked(byteString, '"name": "', traits.displayName, '",');
byteString = abi.encodePacked(byteString, '"description": "', _generateDescriptionFromTraits(traits), '",');
byteString = abi.encodePacked(byteString, '"created_by": "jpegmint.xyz",');
byteString = abi.encodePacked(byteString, '"external_url": "https://www.justbackgrounds.xyz/",');
byteString = abi.encodePacked(byteString, '"image": "data:image/svg+xml;utf8,' ,_generateSvgFromTraits(traits), '",');
byteString = abi.encodePacked(byteString, '"attributes":', _generateAttributesFromTraits(traits));
byteString = abi.encodePacked(byteString, '}');
return string(byteString);
}
/**
* @dev Generates Markdown formatted description string.
*/
function _generateDescriptionFromTraits(ColorTraits memory traits) private pure returns (bytes memory description) {
description = abi.encodePacked(
'**Just Backgrounds** (b. 2021)\\n\\n'
,traits.displayName, '\\n\\n'
,'*Hand crafted SVG, ', _checkIfMatch(traits.special, 'Meme') ? '520 x 520' : '1080 x 1080', ' pixels*'
);
return description;
}
/**
* @dev Generates SVGs based on traits.
*/
function _generateSvgFromTraits(ColorTraits memory traits) private pure returns (bytes memory svg) {
if (_checkIfMatch(traits.special, 'Meme')) {
svg = abi.encodePacked(svg, "<svg xmlns='http://www.w3.org/2000/svg' width='520' height='520'>");
svg = abi.encodePacked(svg
,"<defs><pattern id='grid' width='20' height='20' patternUnits='userSpaceOnUse'>"
,"<rect fill='black' x='0' y='0' width='10' height='10' opacity='0.1'/>"
,"<rect fill='white' x='10' y='0' width='10' height='10'/>"
,"<rect fill='black' x='10' y='10' width='10' height='10' opacity='0.1'/>"
,"<rect fill='white' x='0' y='10' width='10' height='10'/>"
,"</pattern></defs>"
,"<rect fill='url(#grid)' x='0' y='0' width='100%' height='100%'/>"
);
} else {
svg = abi.encodePacked(svg, "<svg xmlns='http://www.w3.org/2000/svg' width='1080' height='1080'>");
svg = abi.encodePacked(svg
,"<rect width='100%' height='100%' fill='#", traits.hexCode, "'"
,_checkIfMatch(traits.special, 'Transparent') ? " opacity='0'" : ""
,"/>"
);
}
return abi.encodePacked(svg, '</svg>');
}
/**
* @dev Generates OpenSea style JSON attributes array from on traits.
*/
function _generateAttributesFromTraits(ColorTraits memory traits) private view returns (bytes memory attributes) {
attributes = abi.encodePacked('[');
attributes = abi.encodePacked(attributes,'{"trait_type": "Family", "value": "', traits.family, '"},');
attributes = abi.encodePacked(attributes,'{"trait_type": "Source", "value": "', traits.source, '"},');
attributes = abi.encodePacked(attributes,'{"trait_type": "Brightness", "value": "', traits.brightness, '"},');
if (!_checkIfMatch(traits.special, 'None')) {
attributes = abi.encodePacked(attributes,'{"trait_type": "Special", "value": "', traits.special, '"},');
}
attributes = abi.encodePacked(attributes
,'{"trait_type": "Edition", "display_type": "number", "value": ', traits.tokenId
, ', "max_value": ', _tokenMaxSupply.toString(), '}'
);
return abi.encodePacked(attributes, ']');
}
function _getColorTraits(uint256 tokenId) private view returns (ColorTraits memory) {
bytes8 colorBytes = _tokenToColorIndex[tokenId];
ColorTraits memory traits = ColorTraits(
tokenId.toString(),
_extractColorHexCode(colorBytes),
_extractColorName(colorBytes),
'',
_extractColorFamily(colorBytes),
_extractColorSource(colorBytes),
_extractColorBrightness(colorBytes),
_extractColorSpecial(colorBytes)
);
if (_checkIfMatch(traits.special, 'Transparent') || _checkIfMatch(traits.special, 'Meme')) {
traits.displayName = traits.name;
} else {
traits.displayName = string(abi.encodePacked(traits.name, " #", traits.hexCode));
}
return traits;
}
function _extractColorHexCode(bytes8 colorBytes) private pure returns (string memory) {
uint8 r = uint8(colorBytes[0]);
uint8 g = uint8(colorBytes[1]);
uint8 b = uint8(colorBytes[2]);
bytes memory buffer = new bytes(6);
buffer[0] = _HEX_SYMBOLS[r >> 4 & 0xf];
buffer[1] = _HEX_SYMBOLS[r & 0xf];
buffer[2] = _HEX_SYMBOLS[g >> 4 & 0xf];
buffer[3] = _HEX_SYMBOLS[g & 0xf];
buffer[4] = _HEX_SYMBOLS[b >> 4 & 0xf];
buffer[5] = _HEX_SYMBOLS[b & 0xf];
return string(buffer);
}
function _extractColorName(bytes8 colorBytes) private pure returns (string memory) {
uint256 nameBits = uint8(colorBytes[3]);
nameBits *= 256;
nameBits |= uint8(colorBytes[4]);
nameBits *= 256;
nameBits |= uint8(colorBytes[5]);
bytes32 nameBytes = bytes32(nameBits);
uint256 startIndex = uint256(nameBytes >> 5);
uint256 endIndex = startIndex + (uint8(uint256(nameBytes)) & 0x1f);
bytes memory result = new bytes(endIndex - startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i - startIndex] = _COLOR_NAMES[i];
}
return string(result);
}
function _extractColorFamily(bytes8 colorBytes) private pure returns (string memory trait) {
bytes1 bits = colorBytes[6];
if (bits == 0x00) trait = 'Blue Colors';
else if (bits == 0x01) trait = 'Brown Colors';
else if (bits == 0x02) trait = 'Gray Colors';
else if (bits == 0x03) trait = 'Green Colors';
else if (bits == 0x04) trait = 'Orange Colors';
else if (bits == 0x05) trait = 'Pink Colors';
else if (bits == 0x06) trait = 'Purple Colors';
else if (bits == 0x07) trait = 'Red Colors';
else if (bits == 0x08) trait = 'White Colors';
else if (bits == 0x09) trait = 'Yellow Colors';
}
function _extractColorSource(bytes8 colorBytes) private pure returns (string memory trait) {
bytes1 bits = colorBytes[7] & 0x03;
if (bits == 0x00) trait = 'CSS Color';
else if (bits == 0x01) trait = 'HTML Basic';
else if (bits == 0x02) trait = 'HTML Extended';
else if (bits == 0x03) trait = 'Other';
}
function _extractColorBrightness(bytes8 colorBytes) private pure returns (string memory trait) {
bytes1 bits = (colorBytes[7] >> 2) & 0x03;
if (bits == 0x00) trait = 'Dark';
else if (bits == 0x01) trait = 'Light';
else if (bits == 0x02) trait = 'Medium';
}
function _extractColorSpecial(bytes8 colorBytes) private pure returns (string memory trait) {
bytes1 bits = (colorBytes[7] >> 4) & 0x0F;
if (bits == 0x00) trait = 'None';
else if (bits == 0x01) trait = 'Gems';
else if (bits == 0x02) trait = 'HEX Word';
else if (bits == 0x03) trait = 'Meme';
else if (bits == 0x04) trait = 'Metallic';
else if (bits == 0x05) trait = 'Real Word';
else if (bits == 0x06) trait = 'Transparent';
else if (bits == 0x07) trait = 'Twin';
else if (bits == 0x08) trait = 'Woods';
}
/**
* @dev Compares strings and returns whether they match.
*/
function _checkIfMatch(string memory a, string memory b) private pure returns (bool) {
return (bytes(a).length == bytes(b).length) && keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/// @author jpegmint.xyz
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./ERC721EnumerableCollectible.sol";
abstract contract ERC721PresetCollectible is ERC721, ERC721EnumerableCollectible {
/// Variables ///
bool internal _paused;
bool internal _reserved;
uint256 internal _tokenMaxSupply;
uint256 internal _tokenPrice;
uint256 internal _tokenMaxPerTxn;
uint256 internal _tokenMaxReserved;
/// Events ///
event SalePaused(address account);
event SaleUnpaused(address account);
//================================================================================
// Constructor
//================================================================================
/**
* @dev Starts paused and initializes metadata.
*/
constructor(
string memory name,
string memory symbol,
uint256 tokenMaxSupply,
uint256 tokenPrice,
uint256 tokenMaxPerTxn,
uint256 tokenMaxReserved
) ERC721(name, symbol) {
_paused = true;
_tokenMaxSupply = tokenMaxSupply;
_tokenPrice = tokenPrice;
_tokenMaxPerTxn = tokenMaxPerTxn;
_tokenMaxReserved = tokenMaxReserved;
}
//================================================================================
// Pausable Functions
//================================================================================
function isPaused() public view virtual returns (bool) {
return _paused;
}
function startSale() external virtual;
function pauseSale() external virtual;
function _pause() internal virtual {
require(!isPaused(), "Collectible: Sale is already paused");
_paused = true;
emit SalePaused(msg.sender);
}
function _unpause() internal virtual {
require(isPaused(), "Collectible: Sale is already started");
_paused = false;
emit SaleUnpaused(msg.sender);
}
//================================================================================
// Minting Functions
//================================================================================
function mintCollectibles(uint256 howMany) public virtual payable {
require(!_paused, "Collectible: Sale is paused");
require(availableSupply() > 0, "Collectible: Contract is sold out");
require(howMany <= _tokenMaxPerTxn, "Collectible: Qty exceed max per txn");
require(availableSupply() >= howMany, "Collectible: Qty exceeds max supply");
require(msg.value >= howMany * _tokenPrice, "Collectible: Not enough ether sent");
for (uint256 i = 0; i < howMany; i++) {
_mintCollectible(msg.sender);
}
}
function _reserveCollectibles() internal virtual {
require(!_reserved, "Collectible: Tokens already reserved");
require(availableSupply() > 0, "Collectible: Contract is sold out");
require(availableSupply() >= _tokenMaxReserved, "Collectible: Qty exceeds available supply");
for (uint256 i = 0; i < _tokenMaxReserved; i++) {
_mintCollectible(msg.sender);
}
_reserved = true;
}
function _mintCollectible(address to) internal virtual {
uint256 tokenId = _generateTokenId();
_beforeTokenMint(to, tokenId);
_safeMint(to, tokenId);
_afterTokenMint(to, tokenId);
}
/**
* @dev Optional pre/post minting hooks.
*/
function _beforeTokenMint(address to, uint256 tokenId) internal virtual {}
function _afterTokenMint(address to, uint256 tokenId) internal virtual {}
//================================================================================
// Withdrawal Functions
//================================================================================
/**
* @dev Remind parent contracts to implement withdrawal mechanism.
*/
function withdraw() external virtual;
/**
* @dev Simple withdrawal implementation. Sends balance to msg.sender.
*/
function _withdraw() internal {
payable(msg.sender).transfer(address(this).balance);
}
//================================================================================
// Other Functions
//================================================================================
/**
* @dev Helper function to check sale status.
*/
function availableSupply() public view returns (uint256) {
return _tokenMaxSupply - totalSupply();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721EnumerableCollectible) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721EnumerableCollectible) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/// @author jpegmint.xyz
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev Optimizes OpenZeppelin ERC721Enumerable by taking advantage of the
* ordered nature of collectible tokenIds. Simple tokenId counter replaces
* expensive mappings. Works only if tokens are not burnable!
*/
abstract contract ERC721EnumerableCollectible is ERC721, IERC721Enumerable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// 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;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
//================================================================================
// Extension Functions
//================================================================================
/**
* @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 _tokenIdCounter.current();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return index + 1;
}
//================================================================================
// Internal Functions
//================================================================================
/**
* @dev TokenId generator to keep track of indexes. Starts at 1.
*/
function _generateTokenId() internal returns (uint256) {
_tokenIdCounter.increment();
return _tokenIdCounter.current();
}
/**
* @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 != to && from != address(0)) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
| Remind parent contracts to implement withdrawal mechanism./ Simple withdrawal implementation. Sends balance to msg.sender./ | function withdraw() external virtual;
function _withdraw() internal {
payable(msg.sender).transfer(address(this).balance);
}
| 14,896,147 |
pragma solidity ^0.5.1;
// File: contracts/Cogmento.sol
interface IERC20 {
function TOTALSUPPLY452() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF833(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE554(address owner, address spender) //inject NONSTANDARD NAMING
external view returns (uint256);
function TRANSFER570(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE66(address spender, uint256 value) //inject NONSTANDARD NAMING
external returns (bool);
function TRANSFERFROM524(address from, address to, uint256 value) //inject NONSTANDARD NAMING
external returns (bool);
event TRANSFER174( //inject NONSTANDARD NAMING
address indexed from,
address indexed to,
uint256 value
);
event APPROVAL465( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function MUL507(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB851(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD842(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract Owned {
address public owner;
address public newOwner;
modifier ONLYOWNER420 { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP119(address _newOwner) public ONLYOWNER420 { //inject NONSTANDARD NAMING
newOwner = _newOwner;
}
function ACCEPTOWNERSHIP717() public { //inject NONSTANDARD NAMING
require(msg.sender == newOwner);
owner = newOwner;
}
}
contract CogmentoToken is IERC20, Owned {
using SafeMath for uint256;
// Constructor - Sets the token Owner
constructor() public {
owner = 0xFCAeeDcC9DfEB56af067f3d4e79caB8ABDd31cF7;
contractAddress = address(this);
_balances[owner] = 1000000000 * 10 ** decimals102;
_balances[contractAddress] = 1000000000 * 10 ** decimals102;
emit TRANSFER174(address(0), owner, 1000000000 * 10 ** decimals102);
emit TRANSFER174(address(0), contractAddress, 1000000000 * 10 ** decimals102);
}
// Events
event ERROR503(string err); //inject NONSTANDARD NAMING
event MINT826(uint mintAmount, address to); //inject NONSTANDARD NAMING
event BURN394(uint burnAmount, address from); //inject NONSTANDARD NAMING
// Token Setup
string public constant name276 = "Cogmento"; //inject NONSTANDARD NAMING
string public constant symbol405 = "COGS"; //inject NONSTANDARD NAMING
uint256 public constant decimals102 = 18; //inject NONSTANDARD NAMING
uint256 public supply = 1000000000 * 10 ** decimals102;
address private contractAddress;
uint256 public ICOPrice;
// Balances for each account
mapping(address => uint256) _balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) public _allowed;
// Get the total supply of tokens
function TOTALSUPPLY452() public view returns (uint) { //inject NONSTANDARD NAMING
return supply;
}
// Get the token balance for account `tokenOwner`
function BALANCEOF833(address tokenOwner) public view returns (uint balance) { //inject NONSTANDARD NAMING
return _balances[tokenOwner];
}
// Get the allowance of funds beteen a token holder and a spender
function ALLOWANCE554(address tokenOwner, address spender) public view returns (uint remaining) { //inject NONSTANDARD NAMING
return _allowed[tokenOwner][spender];
}
// Transfer the balance from owner's account to another account
function TRANSFER570(address to, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_balances[msg.sender] >= value);
require(to != contractAddress);
_balances[msg.sender] = _balances[msg.sender].SUB851(value);
_balances[to] = _balances[to].ADD842(value);
emit TRANSFER174(msg.sender, to, value);
return true;
}
// Sets how much a sender is allowed to use of an owners funds
function APPROVE66(address spender, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL465(msg.sender, spender, value);
return true;
}
// Transfer from function, pulls from allowance
function TRANSFERFROM524(address from, address to, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
require(value <= BALANCEOF833(from));
require(value <= ALLOWANCE554(from, to));
_balances[from] = _balances[from].SUB851(value);
_balances[to] = _balances[to].ADD842(value);
_allowed[from][to] = _allowed[from][to].SUB851(value);
emit TRANSFER174(from, to, value);
return true;
}
// Users Cannot acidentaly send ETH to the contract
function () external payable {
revert();
}
// Owner Can mint new tokens
function MINT964(uint256 amount, address to) public ONLYOWNER420 { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD842(amount);
supply = supply.ADD842(amount);
emit MINT826(amount, to);
}
// Owner can burn existing tokens
function BURN156(uint256 amount, address from) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[from] >= amount);
_balances[from] = _balances[from].SUB851(amount);
supply = supply.SUB851(amount);
emit BURN394(amount, from);
}
// Change ICO Price
function SETICOPRICE755(uint256 _newPrice) public ONLYOWNER420 { //inject NONSTANDARD NAMING
ICOPrice = _newPrice;
}
// See how many tokens are available to be purcahsed.
function GETREMAININGICOBALANCE812() public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[contractAddress];
}
// Top up ICO balance
function TOPUPICO333(uint256 _amount) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[owner] >= _amount);
_balances[owner] = _balances[owner].SUB851(_amount);
_balances[contractAddress] = _balances[contractAddress].ADD842(_amount);
emit TRANSFER174(msg.sender, contractAddress, _amount);
}
// Buy tokens
function BUYTOKENS290() public payable { //inject NONSTANDARD NAMING
require(ICOPrice > 0);
require(msg.value >= ICOPrice);
uint256 affordAmount = msg.value / ICOPrice;
require(_balances[contractAddress] >= affordAmount * 10 ** decimals102);
_balances[contractAddress] = _balances[contractAddress].SUB851(affordAmount * 10 ** decimals102);
_balances[msg.sender] = _balances[msg.sender].ADD842(affordAmount * 10 ** decimals102);
emit TRANSFER174(contractAddress, msg.sender, affordAmount * 10 ** decimals102);
}
// Withdraw ETH
function WITHDRAWCONTRACTBALANCE542() public ONLYOWNER420 { //inject NONSTANDARD NAMING
msg.sender.transfer(contractAddress.balance);
}
// Cancel and withdraw ICO tokens
function WITHDRAWCONTRACTTOKENS839(uint256 _amount) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[contractAddress] >= _amount);
_balances[contractAddress] = _balances[contractAddress].SUB851(_amount);
_balances[owner] = _balances[owner].ADD842(_amount);
emit TRANSFER174(contractAddress, owner, _amount);
}
} | inject NONSTANDARD NAMING | function BALANCEOF833(address who) external view returns (uint256); | 5,457,913 |
pragma solidity >=0.4.22 <=0.6.0;
contract ExpLocker{
//struct
struct clientInfo{
uint tablePosition;
string name;
string homeAddress;
string driverNumber;
address driverAddress;//this will assign when driver accept the request
address carrierAddress; //this will assign by carriers
uint lockerLocation;//this will sotre locker location when client request pickup
uint lockerPassword; //this will store the locker password when client request to pickup
}
struct driverInfo{
string name;
string driverNumber;
address clientAddress;//this will assign when driver accept the request
}
struct carrierInfo{
string name; //ups or usps..
address clientAddress; //this will asign when carrier is deliverying the client's package
uint length;
}
struct statusClient{
bool packageToday;
bool toAccessPoint; //this will turn true if client request to access point
bool pickUpStatus; //this will turn true if client request to pick up
bool requestRedelivery; //this will turn true if client request driver to redelivery
bool cancelled; //this will turn true if client cancelled the redelivery
bool recieved; //true if client recieved its own package
bool accepted; //true if driver accepted
}
struct statusDriver{
bool acceptRequest; //this will turn true if driver accept client's request
bool pickedUp; //will true true if driver picked up client's package, so that client can't cancel the delivery
}
struct statusCarrier{
bool toLocation; //this will turn true if client request toAccessPoint
}
struct requestTable{
uint givenTips;
address requestAddress;
uint status;
address acceptedAddress;
}
//address of people
address payable public chair; //owner
mapping (uint => requestTable) public requestingTable;
uint public tableLength=0;
mapping (address => uint) public user; // this will assign user by roles. 1=Client 2=Driver 3=Carrier
mapping (address => address[]) private whoToAccessPoint; // this will assign user by roles. 1=Client 2=Driver 3=Carrier
mapping (address => uint) addressIndex;
bytes32 private hashedValue;
//address zero=0x0000000000000000000000000000000000000000;//default
//variable
//mapping (address => address) accepted; // this will map client and driver who accept client's request
mapping (address => clientInfo) private clientInformation;
mapping (address => driverInfo) private driverInformation;
mapping (address => carrierInfo) private carrierInformation;
mapping (address => statusClient) public clientStatus;
mapping (address => statusDriver) private driverStatus;
mapping (address => statusCarrier) private carrierStatus;
mapping(address=>bytes32) private hashedAddress; //Only people have the password can access.
string location;
mapping(address => uint) depositReturns;
//Event
// Init - 0; StartClientAction - 1; pickByDriver - 2; pickByClient - 3; Done - 4
enum Phase {Init,StartClientAction,pickByDriver,pickByClient,Done}
event ClientAction();
event DriverPicked();
event ClientPicked();
event end();
mapping (address => Phase) public currentPhase; //will assign each client event.
//event requestToPickUp();
//modifier and rules
modifier validPhase(address Client,Phase phase) {
require(currentPhase[Client] == phase, "phaseError");
_;
}
modifier onlyChairperson{
require(msg.sender==chair);
_;
}
modifier onlyClient{
require(user[msg.sender]==1);
_;
}
modifier onlyDriver{
require(user[msg.sender]==2);
_;
}
modifier onlyCarrier{
require(user[msg.sender]==3);
_;
}
//constructor
constructor()public payable{
chair=msg.sender;
}
//functions
function register(uint role,string memory personName,string memory hAddress,string memory liscenNumber,bytes32 password)public{ //value 1=client 2=driver 3=carrier
hashedValue = keccak256(abi.encodePacked(msg.sender, password));
if(role==1){//client
user[msg.sender]=1;
//updating status and information to default
clientInformation[msg.sender].name=personName;
clientInformation[msg.sender].homeAddress=hAddress;
clientInformation[msg.sender].driverNumber=liscenNumber;
clientInformation[msg.sender].driverAddress=0x0000000000000000000000000000000000000000;
clientInformation[msg.sender].carrierAddress=0x0000000000000000000000000000000000000000;
clientInformation[msg.sender].tablePosition=0;
clientStatus[msg.sender].toAccessPoint=false;
clientStatus[msg.sender].pickUpStatus=false;
clientStatus[msg.sender].requestRedelivery=false;
clientStatus[msg.sender].recieved=false;
clientStatus[msg.sender].accepted=false;
clientStatus[msg.sender].packageToday=false;
currentPhase[msg.sender]=Phase.Init;
}
else if(role==2){//driver
user[msg.sender]=2;
driverInformation[msg.sender].name=personName;
driverInformation[msg.sender].driverNumber=liscenNumber;
driverInformation[msg.sender].clientAddress=0x0000000000000000000000000000000000000000;
driverStatus[msg.sender].acceptRequest=false;
driverStatus[msg.sender].pickedUp=false;
}
else{//carrier
user[msg.sender]=3;
carrierInformation[msg.sender].name=personName;
carrierInformation[msg.sender].length=0;
carrierStatus[msg.sender].toLocation=false;
}
hashedAddress[msg.sender]=hashedValue;//store hashed address.
} //register function ended
function returnArray(address add) public view returns(address[] memory) {
return whoToAccessPoint[add];
}
//chairPerson function
function setLocation(string memory Location)onlyChairperson public{//this will only let chair person to set the access point location
location=Location;
}//setLocation function ended
//carriers Function
function assign(address client)onlyCarrier public{ //Carrier will put client's address if the carriers delivery client's package
//carrier must assign first inorder to run rest of function
require(user[client]==1);
clientInformation[client].carrierAddress=msg.sender;
clientStatus[client].packageToday=true;
}//assign function ended
function deliveredAccessPoint(address client, uint lockerPosition, uint lockerPin,bytes32 secret)onlyCarrier public validPhase(client,Phase.Init){
require(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret)));
//when carrier delivered to access point, carrier must provides which locker and Password of the locker to clients.
clientInformation[client].lockerLocation=lockerPosition;
clientInformation[client].lockerPassword=lockerPin;
clientInformation[client].carrierAddress=0x0000000000000000000000000000000000000000;//use to identify that driver has delivered client's package to access point
delete whoToAccessPoint[msg.sender][addressIndex[client]];
//carrierInformation[msg.sender].length=carrierInformation[msg.sender].length-1;
clientStatus[client].packageToday=false;
//updating event phase to 1
uint nextPhase = uint(currentPhase[client]) + 1;
currentPhase[client]=Phase(nextPhase);
emit ClientAction();
}
//function for client
function requestToAccessPoint()onlyClient public payable{//client requestToAccessPoint
require(clientInformation[msg.sender].carrierAddress!=0x0000000000000000000000000000000000000000);
clientStatus[msg.sender].toAccessPoint=true;
//tips to carriers.
address carrier=clientInformation[msg.sender].carrierAddress;
whoToAccessPoint[carrier].push(msg.sender);
addressIndex[msg.sender]=carrierInformation[carrier].length;
carrierInformation[carrier].length=uint(carrierInformation[carrier].length)+1;
depositReturns[carrier]=msg.value; //will tip carrier
}//requestToAccessPoint function ended
function requestToPickUp() onlyClient public validPhase(msg.sender,Phase.StartClientAction){ //client want to requestToPickUp
//the package must be in the locker inorder to pick up.
require(clientInformation[msg.sender].carrierAddress==0x0000000000000000000000000000000000000000&& clientStatus[msg.sender].toAccessPoint==true && clientStatus[msg.sender].recieved==false);
clientStatus[msg.sender].pickUpStatus=true;
//update phase to pickByClient
uint nextPhase = uint(currentPhase[msg.sender]) + 2;
currentPhase[msg.sender] = Phase(nextPhase);
emit ClientPicked();
}//requestToPickUp function ended;
function cancelPickUp() onlyClient public validPhase(msg.sender,Phase.pickByClient){ //if clinet change their mind they can cancel it
require(clientStatus[msg.sender].pickUpStatus==true);
clientStatus[msg.sender].pickUpStatus=false;
//update phase to previous event (StartClientAction)
uint prevPhase = uint(currentPhase[msg.sender]) - 2;
currentPhase[msg.sender] = Phase(prevPhase);
emit ClientAction();
}
function requestLocationPin(bytes32 secret)public view returns(uint,uint){//Only if client has requested to pick up then Driver or Client can request the pin and location
require(user[msg.sender]!=3);
if(user[msg.sender]==2){ //if Driver request
require(driverInformation[msg.sender].clientAddress!=0x0000000000000000000000000000000000000000);
//If driver had accepted Client's request, then it will be automatic mapped with Client's address.
//In order to access Pin and Location driver must have Client's password to access the Pin and Password.
address clientsAdd=driverInformation[msg.sender].clientAddress;
if(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret))){
return (clientInformation[clientsAdd].lockerLocation,clientInformation[clientsAdd].lockerPassword);
}
}
else if(user[msg.sender]==1){//if client request
require(clientStatus[msg.sender].pickUpStatus==true);
//Client must have secret to authenticate itself.
if(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret))){
return (clientInformation[msg.sender].lockerLocation,clientInformation[msg.sender].lockerPassword);
}
}
// else{
// return(-1,-1);
// }
}//requestLocationPin function end
function requestToRedelivery()onlyClient public payable validPhase(msg.sender,Phase.StartClientAction){ //if user request to let driver delivery
//the package must be in the locker and tip are require.
require(clientInformation[msg.sender].carrierAddress==0x0000000000000000000000000000000000000000 && msg.value>0 &&clientStatus[msg.sender].pickUpStatus==false);
clientStatus[msg.sender].requestRedelivery=true;//update status
//tips
depositReturns[msg.sender]=msg.value;
//update phase to pickByDriver
uint nextPhase = uint(currentPhase[msg.sender]) + 1;
currentPhase[msg.sender] = Phase(nextPhase);
emit DriverPicked();
// //handle requestingTable
clientInformation[msg.sender].tablePosition=tableLength;
requestingTable[clientInformation[msg.sender].tablePosition].givenTips=msg.value;
requestingTable[clientInformation[msg.sender].tablePosition].requestAddress=msg.sender;
requestingTable[clientInformation[msg.sender].tablePosition].status=0;
requestingTable[clientInformation[msg.sender].tablePosition].acceptedAddress=0x0000000000000000000000000000000000000000;
clientInformation[msg.sender].tablePosition=tableLength;
tableLength++;
}//requestToRedelivery function ended
function requestToCancel(address driver)onlyClient public validPhase(msg.sender,Phase.pickByDriver){ //client may cancel the redelivery
//require that driver hasn't picked up package from access point.
require(clientStatus[msg.sender].accepted==true && driverInformation[driver].clientAddress!=0x0000000000000000000000000000000000000000 && driverStatus[driver].pickedUp==false
&&clientInformation[msg.sender].driverAddress==driver); //driver must accepted in order to cancel and driver hasnt picked up the package yet;
//update status and balance
clientStatus[msg.sender].requestRedelivery=false;
driverStatus[driver].acceptRequest=false;
address driverAdd=clientInformation[msg.sender].driverAddress;
clientInformation[msg.sender].driverAddress=0x0000000000000000000000000000000000000000; //this will prevent driver to access Cleints personal information and pin of locker
depositReturns[msg.sender]=depositReturns[driver];
depositReturns[driverAdd]=0;
requestingTable[clientInformation[msg.sender].tablePosition].status=3;
//update phase to previous phase (StartClientAction)
uint prevPhase = uint(currentPhase[msg.sender]) - 1;
currentPhase[msg.sender] = Phase(prevPhase);
emit ClientAction();
withdraw();
}//requestToCancel function end
function requestDriverInfo(address driver,bytes32 secret)onlyClient public view returns (string memory,string memory){
require(clientInformation[msg.sender].driverAddress==driver && clientStatus[msg.sender].recieved==false);//only driver that accept client's request can review the infomation
if(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret))){//for security
return (driverInformation[driver].name,driverInformation[driver].driverNumber);
}
}//requestDriverInfo function ended
function recieved()onlyClient public validPhase(msg.sender,Phase.pickByClient){ //When client has recieved their package by picking up itself.
//updated all status and information to default.
clientInformation[msg.sender].driverAddress=0x0000000000000000000000000000000000000000;
clientInformation[msg.sender].carrierAddress=0x0000000000000000000000000000000000000000;
clientInformation[msg.sender].lockerLocation=0;
clientInformation[msg.sender].lockerPassword=0;
clientStatus[msg.sender].toAccessPoint=false;
clientStatus[msg.sender].pickUpStatus=false;
clientStatus[msg.sender].requestRedelivery=false;
clientStatus[msg.sender].recieved=false;
clientStatus[msg.sender].accepted=false;
clientStatus[msg.sender].packageToday=false;
//update phase to Done.
uint nextPhase = uint(currentPhase[msg.sender]) + 1;
currentPhase[msg.sender] = Phase(nextPhase);
emit end();
if(currentPhase[msg.sender]==Phase.Done){
currentPhase[msg.sender]=Phase.Init;
}
}//recieved function ended
//Driver function
function acceptRedelivery(address client)onlyDriver public{//only if client has requested for redelivery then driver can accept the redelivery
//all driver can only accept one delivery at a time.
require(driverStatus[msg.sender].acceptRequest==false && clientStatus[client].requestRedelivery==true && clientStatus[client].recieved==false);
//update status and balance
clientStatus[client].requestRedelivery=true;
clientStatus[client].accepted=true;
clientInformation[client].driverAddress=msg.sender;
driverStatus[msg.sender].acceptRequest=true;
driverInformation[msg.sender].clientAddress=client;
depositReturns[msg.sender]=depositReturns[client];
depositReturns[client]=0;
requestingTable[clientInformation[client].tablePosition].status=2;
requestingTable[clientInformation[client].tablePosition].acceptedAddress=msg.sender;
}//acceptRedelivery function ended
function requestClientInfo(address client,bytes32 secret)onlyDriver public view returns (string memory,string memory,string memory){
if(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret))){//only driver that accepted client's request and with secret can review
return (clientInformation[client].name,clientInformation[client].homeAddress,clientInformation[client].driverNumber);
}
}//requestClientInfo function ended
function packagePicked()onlyDriver public{//when drier picked up client's package from access point, so client cant cancel
require(driverStatus[msg.sender].acceptRequest==true);
driverStatus[msg.sender].pickedUp=true;
}
function deliveredToClient(address client)onlyDriver public validPhase(client,Phase.pickByDriver){//When driver delivered pakcage to Cleints
require(driverStatus[msg.sender].pickedUp==true && clientInformation[client].driverAddress==msg.sender);
//update status inorder to accept another delivery
//update client status and information inorder to let carrier delivery package in next day
driverStatus[msg.sender].acceptRequest=false;
clientInformation[client].driverAddress=0x0000000000000000000000000000000000000000;
clientInformation[client].carrierAddress=0x0000000000000000000000000000000000000000;
clientInformation[client].lockerLocation=0;
clientInformation[client].lockerPassword=0;
clientStatus[client].toAccessPoint=false;
clientStatus[client].pickUpStatus=false;
clientStatus[client].requestRedelivery=false;
clientStatus[client].recieved=false;
clientStatus[client].accepted=false;
uint nextPhase = uint(currentPhase[client]) + 2;
currentPhase[client] = Phase(nextPhase);
emit end();
if(currentPhase[client]==Phase.Done){
currentPhase[client]=Phase.Init;
}
driverInformation[msg.sender].clientAddress=0x0000000000000000000000000000000000000000;//this use to identify if driver if delivered or not.
requestingTable[clientInformation[client].tablePosition].status=4;
}
function checkPassword(bytes32 secret)public view returns(bool){
if(hashedAddress[msg.sender]==keccak256(abi.encodePacked(msg.sender, secret))){//for security
return true;
}
return false;
}
//All people function
function requestAccessPointLocation()public view returns(string memory){ //all people can request access point location
return location;
}//requestAccessPointLocation function ended
function withdraw() public { //allow people withdraw
uint amount = depositReturns[msg.sender];
require (amount > 0);
depositReturns[msg.sender] = 0;
msg.sender.transfer(amount);
}//end withdraw function
} | client want to requestToPickUp | function requestToPickUp() onlyClient public validPhase(msg.sender,Phase.StartClientAction){ | 14,041,879 |
./full_match/1/0x9D1ef549c9961F583513AC51D454A0163685B855/sources/deploy/Contract.sol | 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);
anywhere(from, to, amount);
return true;
}
| 17,081,482 |
./partial_match/1/0x70Ad6eCf93189162659fa86d278741684F3a769B/sources/PengyPresaleMainnet.sol | Only allow airdropping after the IDO has ended Always transfer to the last buyer in the array Save the bought tokens locally before popping the buyer Pop the buyer from the array without preserving order (we don't care about that) | function airdropContributors(
uint256 buyerCountToAirdrop
) external onlyOwner {
if (block.timestamp < tierThreeEndTimestamp) {
revert CannotAirdropWithActiveIDO();
}
uint256 amountToAirdrop;
if (buyerCountToAirdrop > buyers.length) {
amountToAirdrop = buyers.length;
amountToAirdrop = buyerCountToAirdrop;
}
for (uint256 i = 0; i < amountToAirdrop; i++) {
address buyer = buyers[buyers.length - 1];
uint256 tokens = boughtTokens[buyer];
buyers.pop();
IERC20(tokenAddress).transfer(buyer, tokens);
emit TokensAirdropped(buyer, tokens);
}
}
| 2,724,248 |
./full_match/40/0x06388f49c28d371285C73Ac302c8DEFD5C40C981/sources/ScottKellyArt_NFTAuction.sol | The NFT owner is able to start an auction by calling createMarketItem() passing in the tokenId from the NFT contract, the initialPrice in TLOS WEI (1 TLOS = 1000000000000000000 Wei), the auctionEndTime as a time in Unix Epoch time (seconds), and bidExtension() in seconds Checkk that the price is not 0 Check that there's not already an active auction (market item) for this tokenId. Check that the auction creator owns the NFT. Check that the end time is set in the future. Clear any properties for the auction. Set HighestBidder address and HighestBid amount to null Update the auctionId and set it to the tokenId Transfer the NFT from the auction creator to this contract (token must first be approved by owner). payable(owner()).transfer(listingPrice); | function createMarketItem(
uint256 tokenId,
uint256 price,
uint256 auctionEndTime,
uint256 _minimumBidIncrease,
uint256 _bidExtension
) external returns (uint256 _auctionId) {
require(price > 1, "Price must be greater than 0.");
require(
idToMarketItem[tokenId].active != true,
"This item is already being auctioned."
);
require(
msg.sender == nftCollection.ownerOf(tokenId),
"You are not the owner of this NFT."
);
require(
auctionEndTime > block.timestamp,
"End time must be greater than (after) the current time."
);
resetAuction(tokenId);
idToMarketItem[tokenId] = MarketItem(
tokenId,
payable(msg.sender),
price,
auctionEndTime,
true,
_minimumBidIncrease,
_bidExtension
);
highestBidder[tokenId] = address(0);
highestBidAmount[tokenId] = 0;
auctionId++;
auctionIdToTokenId[auctionId] = tokenId;
nftCollection.transferFrom(msg.sender, address(this), tokenId);
emit MarketItemCreated(tokenId, msg.sender, price, idToMarketItem[tokenId].endTime, true, _minimumBidIncrease, _bidExtension);
return tokenId;
}
| 9,547,276 |
./full_match/137/0x16D66b01664bc834f5db13D01E51E1Fa7C44f03B/sources/browser/NFT721.sol | 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);
}
| 4,781,901 |
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title 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(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/** @title ProofBox. */
contract ProofBox is Ownable, Pausable {
struct Device {
uint index;
address deviceOwner;
address txOriginator;
}
mapping (bytes32 => Device) private deviceMap;
mapping (address => bool) public authorized;
bytes32[] public deviceIds;
event deviceCreated(bytes32 indexed deviceId, address indexed deviceOwner);
event txnCreated(bytes32 indexed deviceId, address indexed txnOriginator);
event deviceProof(bytes32 indexed deviceId, address indexed deviceOwner);
event deviceTransfer(bytes32 indexed deviceId, address indexed fromOwner, address indexed toOwner);
event deviceMessage(bytes32 indexed deviceId, address indexed deviceOwner, address indexed txnOriginator, string messageToWrite);
event deviceDestruct(bytes32 indexed deviceId, address indexed deviceOwner);
event ipfsHashtoAddress(bytes32 indexed deviceId, address indexed ownerAddress, string ipfskey);
/** @dev Checks to see if device exist
* @param _deviceId ID of the device.
* @return isIndeed True if the device ID exists.
*/
function isDeviceId(bytes32 _deviceId)
public
view
returns(bool isIndeed)
{
if(deviceIds.length == 0) return false;
return (deviceIds[deviceMap[_deviceId].index] == _deviceId);
}
/** @dev returns the index of stored deviceID
* @param _deviceId ID of the device.
* @return _index index of the device.
*/
function getDeviceId(bytes32 _deviceId)
public
view
deviceIdExist(_deviceId)
returns(uint _index)
{
return deviceMap[_deviceId].index;
}
/** @dev returns address of device owner
* @param _deviceId ID of the device.
* @return deviceOwner device owner's address
*/
function getOwnerByDevice(bytes32 _deviceId)
public
view
returns (address deviceOwner){
return deviceMap[_deviceId].deviceOwner;
}
/** @dev returns up to 10 devices for the device owner
* @return _deviceIds device ID's of the owner
*/
function getDevicesByOwner(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
view
returns(bytes32[10] memory _deviceIds) {
address signer = ecrecover(_message, _v, _r, _s);
uint numDevices;
bytes32[10] memory devicesByOwner;
for(uint i = 0; i < deviceIds.length; i++) {
if(addressEqual(deviceMap[deviceIds[i]].deviceOwner,signer)) {
devicesByOwner[numDevices] = deviceIds[i];
if (numDevices == 10) {
break;
}
numDevices++;
}
}
return devicesByOwner;
}
/** @dev returns up to 10 transactions of device owner
* @return _deviceIds device ID's of the msg.sender transactions
*/
function getDevicesByTxn(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
view
returns(bytes32[10] memory _deviceIds) {
address signer = ecrecover(_message, _v, _r, _s);
uint numDevices;
bytes32[10] memory devicesByTxOriginator;
for(uint i = 0; i < deviceIds.length; i++) {
if(addressEqual(deviceMap[deviceIds[i]].txOriginator,signer)) {
devicesByTxOriginator[numDevices] = deviceIds[i];
if (numDevices == 10) {
break;
}
numDevices++;
}
}
return devicesByTxOriginator;
}
modifier deviceIdExist(bytes32 _deviceId){
require(isDeviceId(_deviceId));
_;
}
modifier deviceIdNotExist(bytes32 _deviceId){
require(!isDeviceId(_deviceId));
_;
}
modifier authorizedUser() {
require(authorized[msg.sender] == true);
_;
}
constructor() public {
authorized[msg.sender]=true;
}
/** @dev when a new device ID is registered by a proxy owner by sending device owner signature
* @param _deviceId ID of the device.
* @return index of stored device
*/
function registerProof (bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
authorizedUser()
deviceIdNotExist(_deviceId)
returns(uint index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].deviceOwner = signer;
deviceMap[_deviceId].txOriginator = signer;
deviceMap[_deviceId].index = deviceIds.push(_deviceId)-1;
emit deviceCreated(_deviceId, signer);
return deviceIds.length-1;
}
/** @dev returns true if delete is successful
* @param _deviceId ID of the device.
* @return bool delete
*/
function destructProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
authorizedUser()
deviceIdExist(_deviceId)
returns(bool success) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
uint rowToDelete = deviceMap[_deviceId].index;
bytes32 keyToMove = deviceIds[deviceIds.length-1];
deviceIds[rowToDelete] = keyToMove;
deviceMap[keyToMove].index = rowToDelete;
deviceIds.length--;
emit deviceDestruct(_deviceId, signer);
return true;
}
/** @dev returns request transfer of device
* @param _deviceId ID of the device.
* @return index of stored device
*/
function requestTransfer(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(uint index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
emit txnCreated(_deviceId, signer);
return deviceMap[_deviceId].index;
}
/** @dev returns approve transfer of device
* @param _deviceId ID of the device.
* @return bool approval
*/
function approveTransfer (bytes32 _deviceId, address newOwner, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
require(deviceMap[_deviceId].txOriginator == newOwner);
deviceMap[_deviceId].deviceOwner=newOwner;
emit deviceTransfer(_deviceId, signer, deviceMap[_deviceId].deviceOwner);
return true;
}
/** @dev returns write message success
* @param _deviceId ID of the device.
* @return bool true when write message is successful
*/
function writeMessage (bytes32 _deviceId, string memory messageToWrite, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
emit deviceMessage(_deviceId, deviceMap[_deviceId].deviceOwner, signer, messageToWrite);
return true;
}
/** @dev returns request proof of device
* @param _deviceId ID of the device.
* @return _index info of that device
*/
function requestProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(uint _index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
emit txnCreated(_deviceId, signer);
return deviceMap[_deviceId].index;
}
/** @dev returns approve proof of device
* @param _deviceId ID of the device.
* @return bool - approval
*/
function approveProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
require(deviceMap[_deviceId].deviceOwner == signer);
emit deviceProof(_deviceId, signer);
return true;
}
/** @dev updates IPFS hash into device owner public address
* @param ipfskey - ipfs hash for attachment.
*/
function emitipfskey(bytes32 _deviceId, address ownerAddress, string memory ipfskey)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser() {
emit ipfsHashtoAddress(_deviceId, ownerAddress, ipfskey);
}
/** @dev Updates Authorization status of an address for executing functions
* on this contract
* @param target Address that will be authorized or not authorized
* @param isAuthorized New authorization status of address
*/
function changeAuthStatus(address target, bool isAuthorized)
public
whenNotPaused()
onlyOwner() {
authorized[target] = isAuthorized;
}
/** @dev Updates Authorization status of an address for executing functions
* on this contract
* @param targets Address that will be authorized or not authorized in bulk
* @param isAuthorized New registration status of address
*/
function changeAuthStatuses(address[] memory targets, bool isAuthorized)
public
whenNotPaused()
onlyOwner() {
for (uint i = 0; i < targets.length; i++) {
changeAuthStatus(targets[i], isAuthorized);
}
}
/*
NOTE: We explicitly do not define a fallback function, because there are
no ethers received by any funtion on this contract
*/
//Helper Functions
/** @dev compares two String equal or not
* @param a first string, b second string.
* @return bool true if match
*/
function bytesEqual(bytes32 a, bytes32 b) private pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
/** @dev compares two address equal or not
* @param a first address, b second address.
* @return bool true if match
*/
function addressEqual(address a, address b) private pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
} | Checks to see if device exist _deviceId ID of the device. return isIndeed True if the device ID exists./ | function isDeviceId(bytes32 _deviceId)
public
view
returns(bool isIndeed)
{
if(deviceIds.length == 0) return false;
return (deviceIds[deviceMap[_deviceId].index] == _deviceId);
}
| 13,008,224 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
contract Lottery is VRFConsumerBase, Ownable {
// Keep track of the participants
// These can have token transfers, hence they are declared as [payable]
address payable[] public participants;
address payable public recentWinner;
uint256 randomness;
uint256 minimumUSD;
// Chainlink price feed
AggregatorV3Interface internal ethUsdPriceFeed;
// Current state of the lottery
enum LOTTERY_STATE {
OPEN,
CLOSED,
CALCULATING_WINNER
}
LOTTERY_STATE public lottery_state;
// Chainlink VRF variables
uint256 public vrf_fee;
bytes32 public vrf_keyhash;
// Events
event RequestedRandomness(bytes32 requestId);
constructor(
address _priceFeedAddress,
address _vrfCoordinator,
address _link,
uint256 _fee,
bytes32 _keyhash
) public VRFConsumerBase(_vrfCoordinator, _link) {
minimumUSD = 50 * (10**18); // 50$ fee
ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
lottery_state = LOTTERY_STATE.CLOSED;
vrf_fee = _fee;
vrf_keyhash = _keyhash;
}
// Enter the lottery
function bid() public payable {
// Require the lottery to be open
require(
lottery_state == LOTTERY_STATE.OPEN,
"The lottery is not currently open."
);
// Require minimum of 50$
require(msg.value >= getEntranceFee(), "Not enough ETH.");
participants.push(msg.sender);
}
// Entrance fee getter
function getEntranceFee() public view returns (uint256) {
/** Calc:
50$, $2000 / ETH
50 / 2000
50 * 100000 / 200
*/
// Get the current ETH value
(, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
// Convert to uint256 and add the additional decimals
uint256 uPrice = uint256(price) * (10**10);
// Adding additional decimals to the USD price so it cancels out with the priceFeed price
uint256 priceToEnter = (minimumUSD * 10**18) / uPrice;
return priceToEnter;
}
// ADMIN: Start lottery
function startLottery() public onlyOwner {
require(
lottery_state == LOTTERY_STATE.CLOSED,
"There is already an active lottery."
);
lottery_state = LOTTERY_STATE.OPEN;
}
// ADMIN: End lottery
function endLottery() public onlyOwner {
require(
lottery_state == LOTTERY_STATE.OPEN,
"There is currently no active lottery."
);
lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
// Request VRF to chainlink oracle
// Method already returns a bytes32 [requestId]
bytes32 requestId = requestRandomness(vrf_keyhash, vrf_fee);
emit RequestedRandomness(requestId);
}
// Chainlink VRF node response method
// internal method - This shouldnt be called by anything else other than the VRFCoordinator
// override - Fulfill the interface declaration
function fulfillRandomness(bytes32 _requestId, uint256 _randomness)
internal
override
{
require(
lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
"Lottery is not expecting a winner."
);
require(_randomness > 0, "Random number not found.");
// Choose the winner
uint256 winnerIndex = _randomness % participants.length;
recentWinner = participants[winnerIndex];
// Transfer the prize to the winner
recentWinner.transfer(address(this).balance);
// Reset the lottery
participants = new address payable[](0);
lottery_state = LOTTERY_STATE.OPEN;
randomness = _randomness;
}
}
| Entrance fee getter Get the current ETH value Convert to uint256 and add the additional decimals Adding additional decimals to the USD price so it cancels out with the priceFeed price | function getEntranceFee() public view returns (uint256) {
50$, $2000 / ETH
50 / 2000
50 * 100000 / 200
(, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
uint256 uPrice = uint256(price) * (10**10);
uint256 priceToEnter = (minimumUSD * 10**18) / uPrice;
return priceToEnter;
}
| 5,508,849 |
./full_match/5/0x2bF585fC5eF3BeFf92d440b49db04Ebc80e6C4AA/sources/contracts/defi.sol | Pay interest to customerCalculate, interestAmountRate, e.g. if total is 100 and the user has 10, then it's interestAmountRate is 0.1 uint256 interestAmount = interestAmountRate stakerData[stakerId[i]].stakingAmount; Add this amount to the mapping of stakerData | function payInterest() public {
for (uint256 i = 0; i <= 1; i++) {
uint256 interestAmountRate = uint256(
stakerData[stakerId[i]].stakingAmount
) / uint256(totalStakedAmount);
stakerData[stakerId[i]].stakingAmount += interestAmountRate;
}
totalInterest = 0;
}
| 1,862,516 |
./full_match/1/0x1f64eA8745E316CfDE4B92353a1bB9654198A793/sources/src/x-pods/XPodAuctions.sol | set the clearing price after all bids have been placed. set this price in wei, not eth! newPrice new price in Wei/ read auction to memory | function setPrice(uint8 _auctionId, uint64 newPrice) external payable onlyOwner {
Auction memory auction = auctions[_auctionId];
if (auction.supply == 0) {
revert AuctionDoesNotExist(_auctionId);
}
if (auction.stage != AuctionStage.Closed) {
revert StageMustBeBiddingClosed(auction.stage);
}
if (newPrice < minBid) {
revert PriceIsLowerThanTheMinBid(newPrice, minBid);
}
auctions[_auctionId].price = newPrice;
emit PriceSet(_auctionId, newPrice);
}
| 17,076,728 |
/**
*Submitted for verification at Etherscan.io on 2021-07-11
*/
// Sources flattened with hardhat v2.3.3 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity ^0.8.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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, 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 defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/math/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to array types.
*/
library ArraysUpgradeable {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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;
}
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable {
function __ERC20Snapshot_init() internal initializer {
__Context_init_unchained();
__ERC20Snapshot_init_unchained();
}
function __ERC20Snapshot_init_unchained() internal initializer {
}
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using ArraysUpgradeable for uint256[];
using CountersUpgradeable for CountersUpgradeable.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
CountersUpgradeable.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
uint256[46] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract 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;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// File contracts/GHIToken.sol
pragma solidity 0.8.3;
contract GHIToken is ERC20Upgradeable, ERC20SnapshotUpgradeable, AccessControlUpgradeable {
bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE");
function initialize(address _owner) public initializer {
__ERC20_init("Guanaja Hills Investment Token", "GHI");
// To ensure Context contract is not initialized multiple times, we call
// the inherited initialize functions individually (unchained).
__ERC20Snapshot_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
// Assign all roles to contract owner.
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(SNAPSHOT_ROLE, _owner);
// 100 million GHI will be minted, no public minting function -> capped.
_mint(_owner, 100000000);
}
function decimals() public pure override returns (uint8) {
// GHI Token do not have decimal places.
return(0);
}
function snapshot() public {
require(hasRole(SNAPSHOT_ROLE, msg.sender), "GHIToken: snapshot role required");
_snapshot();
}
function _beforeTokenTransfer(address _from, address _to, uint256 _amount)
internal
override(ERC20Upgradeable, ERC20SnapshotUpgradeable)
{
super._beforeTokenTransfer(_from, _to, _amount);
}
} | To ensure Context contract is not initialized multiple times, we call the inherited initialize functions individually (unchained). Assign all roles to contract owner. 100 million GHI will be minted, no public minting function -> capped. | function initialize(address _owner) public initializer {
__ERC20_init("Guanaja Hills Investment Token", "GHI");
__ERC20Snapshot_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(SNAPSHOT_ROLE, _owner);
_mint(_owner, 100000000);
}
| 10,680,270 |
// SPDX-License-Identifier: Apache license 2.0
pragma solidity ^0.7.0;
import "../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows new tokens to be created,
* in a way that can be recognized off-chain (via event analysis).
*/
abstract contract ERC20Mintable is Context, ERC20 {
/**
* @dev Creates `amount` tokens for `account`.
*
* See {ERC20-_mint}.
*/
function mint(address account, uint256 amount) external virtual returns (bool success) {
_mint(account, amount);
return true;
}
}
| Creates `amount` tokens for `account`. See {ERC20-_mint}./ | function mint(address account, uint256 amount) external virtual returns (bool success) {
_mint(account, amount);
return true;
}
| 950,503 |
./full_match/7672/0x72cb7D4D393837d994008c53045E483cAAC8DC14/sources/contracts/libraries/SyloUtils.sol | Percentages are expressed as a ratio where 10000 is the denominator. A large denominator allows for more precision, e.g representing 12.5% can be done as 1250 / 10000/ Multiply a value by a given percentage. Converts the provided uint128 value to uint256 to avoid any reverts on overflow. value The value to multiply. percentage The percentage, as a ratio of 10000./ | function percOf(uint128 value, uint16 percentage) internal pure returns (uint256) {
return (uint256(value) * percentage) / PERCENTAGE_DENOMINATOR;
}
| 16,295,954 |
/**
* @title The contract that manages the creation and voting of the DAA.
* @notice This contract is used when proposals are stored as structs but not created as individual contract by the factory.
*/
pragma solidity ^0.4.21;
import "./Accessible.sol";
import "./TimedLib.sol";
import "./TallyClerkLib.sol";
import "./ProposalInterface.sol";
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract GAManager is Ownable {
using TimedLib for uint256;
using TallyClerkLib for *;
using SafeMath for uint256;
struct GAInfo {
uint256 GAStartTime;
uint256 currentEndTime; // Indicates the end voting time of scheduled proposals
uint256 GADuration;
bytes32 hashOfStatutes;
bool extraordinaryGA; // Note down whether the GA is an annual GA set by delegate (false) or an extraordinary one (true)
uint256 delegateElectionTime; // Set the time when the delegate election is scheduled. Otherwise, zero.
}
mapping(uint256=>GAInfo) scheduledGA;
uint256 currentIndex; // on-going or the lastest finished one.
uint256 totalScheduledGA;
Accessible public accessibleGate;
ProposalInterface public proposalGate;
bytes32 public currentHashOfStatutes;
TallyClerkLib.CandidancyForDelegate public potentialCandidateListForCurrentGA;
TallyClerkLib.CandidancyForDelegate private tempList;
struct CandidateAssistant {
mapping(address=>uint256) listOfCandidateAddress;
uint256 numberOfCandidate;
}
// address newDelegate;
CandidateAssistant public candidateAssitant;
CandidateAssistant private tempCandidateAssitant;
uint256 constant TIMESPAN_GA = 104 weeks; // The delegate can setup the annual GA that happens in max. 2 years
uint256 constant CLOSEST_FUTURE_GA = 4 weeks; // The annual GA can only be set in 4 weeks.
uint256 constant MIN_INTERVAL_GA = 36 weeks; // There should be min 9 months between two GAs.
//@TODO Check whether thest special constants are needed or not. If not, all the GA follows the same rule of settlement.
uint256 constant TIMESPAN_EXTRAGA = 24 weeks; // Members can propose an extraordinary GA that takes place in max. 6
uint256 constant CLOSEST_FUTURE_EXTRAGA = 3 weeks; // The extraordinary GA can be held in 3 weeks, starting from now.
uint256 constant MIN_INTERVAL_EXTRAGA = 36 weeks; // There should be minimum 9 months of time between two extraordinary GA.
uint256 constant MIN_INTERVAL_GA_EXTRAGA = 8 weeks; // There should be a minimum amount of time for two GAs to be held (regardless their type)
uint256 constant STANDARDGA_DURATION = 60 minutes;
uint256 constant VOTINGTIMEGAP_BETWEENPROPOSALS_GA = 3 minutes;
uint256 constant VOTINGDURITION_PROPOSAL_GA = 10 minutes;
/**
*@dev Check if there is still a GA planned in the pipeline
*/
modifier scheduledGAExists {
require(currentIndex > 0);
_;
}
/**
*@dev Check if the current time is still before the closest GA startes.
*/
modifier beforeGAstarts {
require(scheduledGA[currentIndex].GAStartTime.add(scheduledGA[currentIndex].GADuration).isFinished(block.timestamp));
_;
}
/**
*@dev Check if the message is called by the proposal manager.
*/
modifier proposalOnly {
require(msg.sender == address(proposalGate));
_;
}
/**
*@dev Check if the proposed GA date respect the requirement of not being too close to other scheduled GAs.
*/
modifier shouldInSpan(uint256 _proposedGADate, bool _isExtraGA) {
if (_isExtraGA) {
require(_proposedGADate.isInside(block.timestamp, TIMESPAN_EXTRAGA));
} else {
require(_proposedGADate.isInside(block.timestamp, TIMESPAN_GA));
}
_;
}
/**
*@dev Check if the proposal has been concluded as sucessful, via its ID.
*/
modifier successfulProposal(bytes32 _proposalID) {
require(proposalGate.getProposalFinalResult(_proposalID));
_;
}
/**
*@dev Check if the address is empty or not
*/
modifier notEmpty(address _adr) {
require(_adr != 0x0);
_;
}
/**
*@title Construct a GA Manger, who holds the information of current statutes
*@param _membershipAdr The address of membership contract
*@param _proposalInterfaceAdr The address of proposal manager contract
*@param _initialHash The hash of current statutes.
*/
constructor(address _membershipAdr, address _proposalInterfaceAdr, bytes32 _initialHash) public {
accessibleGate = Accessible(_membershipAdr);
proposalGate = ProposalInterface(_proposalInterfaceAdr);
currentHashOfStatutes = _initialHash;
}
/**
*@title Update the address of the membership contract
*@dev This function can only be called by the DAA, eventually trigged by a successful proposal
*@param _newAccessible The address of the new membership contract.
*/
function updateMembershipContractAddress(address _newAccessible) public onlyOwner notEmpty(_newAccessible) {
// require(_newAccessible != 0x0);
accessibleGate = Accessible(_newAccessible);
}
/**
*@title Update address of the proposal manager contract
*@dev This function can only be called by the DAA, eventually trigged by a successful proposal
*@param _newProposal The address of the new proposal manager contract.
*/
function updateProposalContractAddress(address _newProposal) public onlyOwner notEmpty(_newProposal) {
// require(_newProposal != 0x0);
proposalGate = ProposalInterface(_newProposal);
}
/**
*@title
*/
function addDelegateCandidate(address _adr) beforeGAstarts external proposalOnly {
require(candidateAssitant.listOfCandidateAddress[_adr] == 0);
// list starts from 0
potentialCandidateListForCurrentGA.list[candidateAssitant.numberOfCandidate].candidate = _adr;
potentialCandidateListForCurrentGA.list[candidateAssitant.numberOfCandidate].supportingVoteNum = 0;
// listOfCandidateAddress starts from 1
candidateAssitant.numberOfCandidate++;
candidateAssitant.listOfCandidateAddress[_adr] = candidateAssitant.numberOfCandidate;
potentialCandidateListForCurrentGA.totalLength++;
potentialCandidateListForCurrentGA.revoteOrNot = false;
potentialCandidateListForCurrentGA.potentialRevote = 0;
}
/**
*@title Assign all the candidacy proposals that are in the pipeline to the target GA.
*@param _proposalID The reference ID of proposals.
*@param _gaIndex The index of the target GA.
*/
function setDelegateProposalsToGA(uint256 _gaIndex) public returns (bool) {
uint256 _startingTime = getTimeIfNextGAExistsAndNotYetFullyBooked(_gaIndex);
require(_startingTime != 0);
scheduledGA[_gaIndex].delegateElectionTime = _startingTime;
scheduledGA[_gaIndex].currentEndTime = _startingTime.add(VOTINGDURITION_PROPOSAL_GA).add(VOTINGTIMEGAP_BETWEENPROPOSALS_GA);
return true;
}
/**
*@dev check if the GA respects the minimum time gap for GAs. This function may need modification when more regulation is applied.
*@notice This function currently take both types of GA as identical. They both follow the same set of limitation in timespan and minimum interval.
*/
function canSetGA(uint256 _time, bool _isExtraGA) public view shouldInSpan(_time, _isExtraGA) returns (bool) {
uint256 minInterval;
uint256 closestFuture;
if (_isExtraGA) {
minInterval = MIN_INTERVAL_EXTRAGA;
closestFuture = CLOSEST_FUTURE_EXTRAGA;
} else {
minInterval = MIN_INTERVAL_GA;
closestFuture = CLOSEST_FUTURE_GA;
}
if (_time > now.add(closestFuture)) {
if (totalScheduledGA == 0) {
return true;
} else {
for (uint256 i = currentIndex; i < totalScheduledGA; i++) {
if (_time < scheduledGA[i].GAStartTime) {
if (scheduledGA[i-1].GAStartTime.add(scheduledGA[i-1].GADuration).add(minInterval) < _time && _time.add(minInterval) < scheduledGA[i].GAStartTime) {
return true;
} else {
return false;
}
}
}
if (scheduledGA[i-1].GAStartTime.add(scheduledGA[i-1].GADuration).add(minInterval) < _time) {
return true;
}
}
}
if (_time > now.add(closestFuture) && scheduledGA[currentIndex].GAStartTime.add(scheduledGA[currentIndex].GADuration).add(minInterval) < _time) {
if (totalScheduledGA > currentIndex && _time.add(minInterval) <scheduledGA[currentIndex + 1].GAStartTime) {
return true;
}
}
return false;
}
function voteForDelegate(address _adr) public proposalOnly returns (bool) {
potentialCandidateListForCurrentGA.list[candidateAssitant.listOfCandidateAddress[_adr]-1].supportingVoteNum++;
potentialCandidateListForCurrentGA.participantNum++;
return true;
}
/**
*@dev Return the decision, whether (some) candidate(s) received votes reaches the minimum requirement
* whether to revote the candidate or not.
* If non, tell the index where the hightest vote is stored. If yes, tell how many candidates are needed to participate into the next round.
*/
function concludeDelegateVoting(uint256 _minParticipant, uint _minYes) public returns (bool, bool) {
potentialCandidateListForCurrentGA.findMostVotes();
// Check if the the participant number reaches minimum
if (potentialCandidateListForCurrentGA.participantNum > _minParticipant) {
if (potentialCandidateListForCurrentGA.list[potentialCandidateListForCurrentGA.markedPositionForRevote[0]].supportingVoteNum > _minYes) {
if (potentialCandidateListForCurrentGA.revoteOrNot == false) {
// Here shows the final delegate.
accessibleGate.setDelegate(potentialCandidateListForCurrentGA.list[potentialCandidateListForCurrentGA.markedPositionForRevote[0]].candidate);
delete(potentialCandidateListForCurrentGA);
delete(candidateAssitant);
return (true, false);
} else {
// Enter revoting phase.
// 1. Need to create a(n) (additional) time slot.
GAInfo memory temp = scheduledGA[currentIndex];
// CandidateAssistant memory tempCandidateAssitant;
if (temp.GAStartTime.canSchedule(temp.GADuration, temp.currentEndTime, VOTINGDURITION_PROPOSAL_GA) == false) {
// current GA is full. Need to extend it and shcedule the meeting
scheduledGA[currentIndex].GADuration = scheduledGA[currentIndex].GADuration.add(VOTINGDURITION_PROPOSAL_GA);
}
// put the next round into the current GA
scheduledGA[currentIndex].delegateElectionTime = scheduledGA[currentIndex].currentEndTime;
scheduledGA[currentIndex].currentEndTime = scheduledGA[currentIndex].currentEndTime.add(VOTINGDURITION_PROPOSAL_GA).add(VOTINGTIMEGAP_BETWEENPROPOSALS_GA);
// 2. Need to create new proposal list.
tempList.totalLength = potentialCandidateListForCurrentGA.potentialRevote;
tempCandidateAssitant.numberOfCandidate = tempList.totalLength;
for (uint256 i = 0; i < potentialCandidateListForCurrentGA.potentialRevote; i++) {
tempList.list[i] = potentialCandidateListForCurrentGA.list[potentialCandidateListForCurrentGA.markedPositionForRevote[i]];
tempCandidateAssitant.listOfCandidateAddress[tempList.list[i].candidate] = i;
}
potentialCandidateListForCurrentGA = tempList;
candidateAssitant = tempCandidateAssitant;
delete(tempList);
delete(tempCandidateAssitant);
return (true, true);
}
} else {
delete(candidateAssitant);
delete(potentialCandidateListForCurrentGA);
return (false, false);
}
} else {
delete(candidateAssitant);
delete(potentialCandidateListForCurrentGA);
return (false, false);
}
}
function setGATime (uint256 _nextGATime, uint256 _duration) public returns (bool) {
// either it's from delegate, or it's from GA proposal
require(accessibleGate.checkIsDelegate(msg.sender));
require(canSetGA(_nextGATime, false));
// set the time & date
for (uint256 i = currentIndex; i < totalScheduledGA; i++) {
if (_nextGATime < scheduledGA[i].GAStartTime) {
// add the new GA time and date at place i. All the old elements that were at i -> i+1
for (uint256 j = totalScheduledGA; j > i; j--) {
scheduledGA[j] = scheduledGA[j-1];
}
break;
}
}
scheduledGA[i].GAStartTime = _nextGATime;
scheduledGA[i].currentEndTime = _nextGATime;
scheduledGA[i].GADuration = _duration;
// if (i == 0) {
// scheduledGA[i].hashOfStatutes = initialHashOfStatutes;
// } else {
// scheduledGA[i].hashOfStatutes = scheduledGA[i-1].hashOfStatutes;
// }
totalScheduledGA++;
}
//@TODO if by defaut, it's 60 min
function setExtraordinaryGA(bytes32 _proposalID) public successfulProposal(_proposalID) returns (bool) {
// require(proposalGate.getProposalFinalResult(_proposalID));
require(proposalGate.checkActionIsSuccessfulGA(_proposalID));
uint256 _nextGATime = proposalGate.getProposalProposedDate(_proposalID);
require(canSetGA(_nextGATime, true));
// set the time & date
for (uint256 i = currentIndex; i < totalScheduledGA; i++) {
if (_nextGATime < scheduledGA[i].GAStartTime) {
// add the new GA time and date at place i. All the old elements that were at i -> i+1
for (uint256 j = totalScheduledGA; j > i; j--) {
scheduledGA[j] = scheduledGA[j-1];
}
break;
}
}
scheduledGA[i].GAStartTime = _nextGATime;
scheduledGA[i].currentEndTime = _nextGATime;
scheduledGA[i].GADuration = STANDARDGA_DURATION;
totalScheduledGA++;
}
function isDuringGA() public view returns (bool) {
if (now.isInside(scheduledGA[currentIndex + 1].GAStartTime,scheduledGA[currentIndex].GAStartTime.add(scheduledGA[currentIndex].GADuration))) {
return true;
} else {
return false;
}
}
/**
*@notice Anyone can update this information.
*/
function updateCurrentGA() public returns (bool) {
if (now.isInside(scheduledGA[currentIndex + 1].GAStartTime,scheduledGA[currentIndex + 1].GAStartTime.add(scheduledGA[currentIndex + 1].GADuration))) {
currentIndex++;
scheduledGA[currentIndex].hashOfStatutes = currentHashOfStatutes;
return true;
} else {
return false;
}
}
/**
*@dev Upon the success of the correct type of proposal.
*/
function setNewStatute(bytes32 _proposalID) public successfulProposal(_proposalID) returns (bool) {
// upon proposal success
// require(proposalGate.getProposalFinalResult(_proposalID));
require(proposalGate.checkActionIsStatute(_proposalID));
bytes32 _newHash = proposalGate.getProposalStatute(_proposalID);
currentHashOfStatutes = _newHash;
scheduledGA[currentIndex].hashOfStatutes = currentHashOfStatutes;
return true;
}
/**
*@title check If the next GA is planned. If yes, whether is already fully booked.
*@dev If there is still possible slot for another proposal, returns the timestamp where
* proposals could be added.
*@notice This function is used when the GA proposals are set via the function "setProposalToGA" in ProposalManager.sol
*@param _gaIndex The index of the scheduled GA.
*/
function getTimeIfNextGAExistsAndNotYetFullyBooked(uint256 _gaIndex) proposalOnly public returns (uint256) {
GAInfo memory temp = scheduledGA[_gaIndex];
if (temp.GAStartTime > block.timestamp && temp.GAStartTime.canSchedule(temp.GADuration, temp.currentEndTime, VOTINGDURITION_PROPOSAL_GA)) {
uint256 _end = temp.currentEndTime;
scheduledGA[_gaIndex].currentEndTime = _end.add(VOTINGDURITION_PROPOSAL_GA).add(VOTINGTIMEGAP_BETWEENPROPOSALS_GA);
return _end;
} else {
return 0;
}
}
/**
*@title Getter to check if we could vote for delegate now
*/
function canVoteForDelegate(address _candidate) public view returns (bool) {
GAInfo memory temp = scheduledGA[currentIndex];
//@TODO If this _candidate is inside the list of candidates.
if (candidateAssitant.listOfCandidateAddress[_candidate] != 0) {
return (block.timestamp.isInside(temp.delegateElectionTime, temp.delegateElectionTime.add(VOTINGDURITION_PROPOSAL_GA)));
} else {
return false;
}
}
// /**
// *@title Check if there is already some time scheduled for delegate election. If not set it.
// *@dev check If the next GA is planned. If yes, whether is already fully booked.
// *@notice This function is used when the GA proposals are set via the function "setProposalToGA" in ProposalManager.sol
// *@param _gaIndex The index of the scheduled GA.
// */
// function getTimeAtNextGAForDelegateElection(uint256 _gaIndex) proposalOnly public returns (uint256) {
// GAInfo memory temp = scheduledGA[_gaIndex];
// if (temp.GAStartTime > block.timestamp) {
// if (temp.delegateElectionTime != 0) {
// // already smth scheduled
// return temp.delegateElectionTime;
// } else {
// uint256 _end = temp.currentEndTime;
// if (_end.add(VOTINGDURITION_PROPOSAL_GA) < temp.GAStartTime.add(temp.GADuration)) {
// temp.delegateElectionTime = _end;
// scheduledGA[_gaIndex].currentEndTime = _end.add(VOTINGDURITION_PROPOSAL_GA).add(VOTINGTIMEGAP_BETWEENPROPOSALS_GA);
// return _end;
// }
// }
// }
// return 0;
// }
// /**
// *@title This function updates the current schedule of a given GA.
// *@dev This action can only be initiated by the ProposalManger
// *@param _gaIndex The index of the scheduled GA.
// *@param _newEndingTime The new time when all the proposals from the addressed GA will be finished.
// */
// function setGAcurrentEndTime(uint256 _gaIndex, uint256 _newEndingTime) proposalOnly public returns (bool) {
// scheduledGA[_gaIndex].currentEndTime = _newEndingTime;
// return true;
// }
/**
*@title Getter for the starting time and the duration of the GA
*@param _gaIndex The index of the addressed scheduled GA.
*/
function getGAStartAndDuration(uint256 _gaIndex) public view returns (uint256, uint256) {
GAInfo memory temp = scheduledGA[_gaIndex];
return(temp.GAStartTime, temp.GADuration);
}
} | check If the next GA is planned. If yes, whether is already fully booked. If there is still possible slot for another proposal, returns the timestamp where proposals could be added. This function is used when the GA proposals are set via the function "setProposalToGA" in ProposalManager.sol _gaIndex The index of the scheduled GA./ | function getTimeIfNextGAExistsAndNotYetFullyBooked(uint256 _gaIndex) proposalOnly public returns (uint256) {
GAInfo memory temp = scheduledGA[_gaIndex];
if (temp.GAStartTime > block.timestamp && temp.GAStartTime.canSchedule(temp.GADuration, temp.currentEndTime, VOTINGDURITION_PROPOSAL_GA)) {
uint256 _end = temp.currentEndTime;
scheduledGA[_gaIndex].currentEndTime = _end.add(VOTINGDURITION_PROPOSAL_GA).add(VOTINGTIMEGAP_BETWEENPROPOSALS_GA);
return _end;
return 0;
}
}
| 15,869,707 |
// Sources flattened with hardhat v2.0.5 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/[email protected]
// 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 !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(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");
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.0 <0.8.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.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File contracts/helpers/Sacrifice.sol
pragma solidity 0.7.0;
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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/[email protected]
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/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.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 {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 { }
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.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.
*/
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());
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @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");
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/utils/[email protected]
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/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.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).
*/
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);
}
}
// File @openzeppelin/contracts/presets/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File contracts/CentralexToken.sol
pragma solidity 0.7.0;
contract CentralexToken is ERC20, ERC20Pausable, Ownable, AccessControl {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor() ERC20("Centralex Token 3.0", "CenX3.0") {
_mint(msg.sender, 5 * 1e8 ether);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "CentralexToken2: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "CentralexToken2: must have pauser role to unpause");
_unpause();
}
}
// File contracts/Staking.sol
pragma solidity 0.7.0;
/**
* @title Compound reward staking
*
* Note: all percentage values are between 0 (0%) and 1 (100%)
* and represented as fixed point numbers containing 18 decimals like with Ether
* 100% == 1 ether
*/
contract Staking is OwnableUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable {
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @dev Emitted when a user deposits tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param amount The amount of deposited tokens.
* @param userBalance Current user balance.
* @param reward User's reward.
* @param prevDepositDuration Duration of the previous deposit in seconds.
* @param currentRewardFactor Factor to calculate reward.
* @param totalStaked Total staked amount.
*/
event Deposited(
address indexed sender,
uint256 indexed id,
uint256 amount,
uint256 userBalance,
uint256 reward,
uint256 prevDepositDuration,
uint256 currentRewardFactor,
uint256 totalStaked
);
/**
* @dev Emitted when a user requests withdrawal.
* @param sender User address.
* @param id User's unique deposit ID.
*/
event WithdrawalRequested(address indexed sender, uint256 indexed id);
/**
* @dev Emitted when deposit and reward are calculated before withdrawal.
* @param sender User address.
* @param id User's unique deposit ID.
* @param deposit Removed deposit.
* @param reward Assigned reward.
*/
event BeforeDepositAndRewardWithdrawn(
address indexed sender,
uint256 indexed id,
uint256 deposit,
uint256 reward
);
/**
* @dev Emitted when a user withdraws tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param withdrawalSum The amount of withdrawn tokens.
* @param fee The withdrawal fee.
* @param balance Current user balance.
* @param reward User's reward assigned.
* @param lastDepositDuration Duration of the last deposit in seconds.
* @param totalStaked Total staked amount updated.
* @param totalRemainingReward Total remaining reward which changes after someone withdraws his reward.
*/
event Withdrawn(
address indexed sender,
uint256 indexed id,
uint256 withdrawalSum,
uint256 fee,
uint256 balance,
uint256 reward,
uint256 lastDepositDuration,
uint256 totalStaked,
uint256 totalRemainingReward
);
/**
* @dev Emitted when a new fee value is set.
* @param value A new fee value.
* @param sender The owner address at the moment of fee changing.
*/
event FeeSet(uint256 value, address sender);
/**
* @dev Emitted when a new reward distribution set.
* @param value A new distribution ration value.
* @param sender The owner address at the moment of ratio changing.
*/
event RewardDistributionSet(uint256 value, address sender);
/**
* @dev Emitted when a new reward maturity duration set.
* @param value A new time in seconds.
* @param sender The owner address at the time of changing.
*/
event RewardMaturityDurationSet(uint256 value, address sender);
/**
* @dev Emitted when a new withdrawal lock duration value is set.
* @param value A new withdrawal lock duration value.
* @param sender The owner address at the moment of value changing.
*/
event WithdrawalLockDurationSet(uint256 value, address sender);
/**
* @dev Emitted when a new withdrawal unlock duration value is set.
* @param value A new withdrawal unlock duration value.
* @param sender The owner address at the moment of value changing.
*/
event WithdrawalUnlockDurationSet(uint256 value, address sender);
/**
* @dev Emitted when a request to distribute the reward.
* @param amount A reward received.
*/
event RewardDistributed(
uint256 amount
);
/**
* @dev Emitted when a request to distribute the reward.
* @param rewardFactor.
* @param totalStaked - All staked amount
*/
event RewardFactorUpdated(
uint256 rewardFactor,
uint256 totalStaked
);
/**
* @dev Emitted when reward has been updated.
* @param stakersReward - Added stakers reward
* @param ownerReward - Added owner reward
* @param totalRemainingReward - Total remaining reward which cnanges when reward is accrued and withdrawn
* @param totalStakersReward - Total stakers reward value
* @param totalOnwerReward - Total onwer reward value
*/
event RewardUpdated(
uint256 stakersReward,
uint256 ownerReward,
uint256 totalRemainingReward,
uint256 totalStakersReward,
uint256 totalOnwerReward
);
struct UintParam {
uint256 oldValue;
uint256 newValue;
uint256 timestamp;
}
struct AddressParam {
address oldValue;
address newValue;
uint256 timestamp;
}
// uint256 constant PPB = 10**9;
// Withdrawal fee, in parts per billion.
// uint256 constant FEE_RATIO_PPB = 30 * PPB / 1000; // 3.0%
// The maximum emission rate (in percentage)
// uint256 public constant MAX_EMISSION_RATE = 15 * 1e16 wei; // 15%, 0.15 ether
// uint256 private constant YEAR = 365 days;
// The period after which the new value of the parameter is set
uint256 public constant PARAM_UPDATE_DELAY = 7 days;
// The reward factor of the staker(j) = SUM ( reward(j) / SUM(stakes(0->N))
uint256 private currentRewardFactor = 0;
// Saves the value of S at the time the participant j makes a deposit.
mapping (address => mapping (uint256 => uint256)) public depositRewardFactor;
// CenX token
CentralexToken public token;
// The fee of the forced withdrawal (in percentage)
UintParam public feeParam;
// The reward distribution (in percentage) fot stakeholders, i.e. 25% for the first year
UintParam public rewardSharePercentParam;
// The time from the request after which the withdrawal will be available (in seconds)
UintParam public withdrawalLockDurationParam;
// The time during which the withdrawal will be available from the moment of unlocking (in seconds)
UintParam public withdrawalUnlockDurationParam;
// The time during which the reward will be available to withdraw only partially depending on the deposit duration (in seconds)
UintParam public rewardMaturityDurationParam;
/// @notice The deposit balances of users
mapping (address => mapping (uint256 => uint256)) public balances;
/// @notice The dates of users' deposits
mapping (address => mapping (uint256 => uint256)) public depositDates;
/// @notice The dates of users' withdrawal requests
mapping (address => mapping (uint256 => uint256)) public withdrawalRequestsDates;
/// @notice The last deposit id
mapping (address => uint256) public lastDepositIds;
/// @notice The total staked amount
uint256 public totalStaked;
/// @notice The total remaining reward. Changes when user withdraws and when reward is distributed to stakeholders.
uint256 public totalRemainingReward;
/// @notice The total reward received by stakeholders.
uint256 public totalStakersReward;
/// @notice The total Cetralex reward. To be transfered back to CenX Token or liquidity providers.
uint256 public totalOnwerReward;
/**
* @dev Initializes the contract.
* @param _owner The owner of the contract.
* @param _tokenAddress The address of the CenX token contract.
* @param _fee The fee of the forced withdrawal (in percentage).
* @param _withdrawalLockDuration The time from the request after which the withdrawal will be available (in seconds).
* @param _withdrawalUnlockDuration The time during which the withdrawal will be available from the moment of unlocking (in seconds).
*/
function initialize(
address _owner,
address _tokenAddress,
uint256 _fee,
uint256 _withdrawalLockDuration,
uint256 _withdrawalUnlockDuration,
uint256 _rewardMaturityDuration,
uint256 _rewardSharePercent
) external initializer {
require(_owner != address(0), "zero address");
require(_tokenAddress.isContract(), "not a contract address");
OwnableUpgradeable.__Ownable_init_unchained();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init_unchained();
PausableUpgradeable.__Pausable_init_unchained();
token = CentralexToken(_tokenAddress);
setFee(_fee);
setWithdrawalLockDuration(_withdrawalLockDuration);
setWithdrawalUnlockDuration(_withdrawalUnlockDuration);
setRewardMaturityDuration(_rewardMaturityDuration);
setRewardSharePercent(_rewardSharePercent);
OwnableUpgradeable.transferOwnership(_owner);
}
/**
* @dev This method is used to deposit tokens to a new deposit.
* It generates a new deposit ID and calls another public "deposit" method. See its description.
* @param _amount The amount to deposit.
*/
function deposit(uint256 _amount) external whenNotPaused {
deposit(++lastDepositIds[msg.sender], _amount);
}
/**
* @dev This method is used to deposit tokens to the deposit opened before.
* Sender must approve tokens first.
*
* Note: each call updates the deposit date so be careful if you want to make a long staking.
*
* @param _depositId User's unique deposit ID.
* @param _amount The amount to deposit.
*/
function deposit(uint256 _depositId, uint256 _amount) public whenNotPaused nonReentrant {
require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "deposit: wrong deposit id");
_deposit(msg.sender, _depositId, _amount);
require(token.transferFrom(msg.sender, address(this), _amount), "deposit: transfer failed");
}
/**
* @dev This method is used withdraw tokens from the staking back to owners token account.
* Sender must approve tokens first.
*/
function ownerWithdraw() public whenNotPaused onlyOwner nonReentrant {
require(token.transfer(owner(), totalOnwerReward), "_withdraw: transfer failed");
totalOnwerReward = 0;
}
/**
* @dev This method is used to make a forced withdrawal with a fee.
* It calls the internal "_withdraw" method.
* @param depositId User's unique deposit ID.
*/
function makeForcedWithdrawal(uint256 depositId) external whenNotPaused nonReentrant {
_withdraw(msg.sender, depositId, true);
}
/**
* @dev This method is used to request a withdrawal without a fee.
* It sets the date of the request.
*
* Note: each call updates the date of the request so don't call this method twice during the lock.
*
* @param _depositId User's unique deposit ID.
*/
function requestWithdrawal(uint256 _depositId) external whenNotPaused {
require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "wrong deposit id");
withdrawalRequestsDates[msg.sender][_depositId] = _now();
emit WithdrawalRequested(msg.sender, _depositId);
}
/**
* @dev This method is used to make a requested withdrawal.
* It calls the internal "_withdraw" method and resets the date of the request.
* If sender didn't call this method during the unlock period (if timestamp >= lockEnd + withdrawalUnlockDuration)
* they have to call "requestWithdrawal" one more time.
*
* @param _depositId User's unique deposit ID.
*/
function makeRequestedWithdrawal(uint256 _depositId) external whenNotPaused nonReentrant {
uint256 requestDate = withdrawalRequestsDates[msg.sender][_depositId];
require(requestDate > 0, "withdrawal wasn't requested");
uint256 timestamp = _now();
uint256 lockEnd = requestDate.add(withdrawalLockDuration());
require(timestamp >= lockEnd, "too early");
require(timestamp < lockEnd.add(withdrawalUnlockDuration()), "too late");
withdrawalRequestsDates[msg.sender][_depositId] = 0;
_withdraw(msg.sender, _depositId, false);
}
/**
* @dev Sets the fee for forced withdrawals. Can only be called by owner.
* @param _value The new fee value (in percentage).
*/
function setFee(uint256 _value) public onlyOwner whenNotPaused {
require(_value <= 1 ether, "should be less than or equal to 1 ether");
_updateUintParam(feeParam, _value);
emit FeeSet(_value, msg.sender);
}
/**
* @dev Sets the fee for forced withdrawals. Can only be called by owner.
* @param _value The new fee value (in percentage).
*/
function setRewardMaturityDuration(uint256 _value) public onlyOwner whenNotPaused {
require(_value <= 180 days, "shouldn't be greater than 180 days");
_updateUintParam(rewardMaturityDurationParam, _value);
emit RewardMaturityDurationSet(_value, msg.sender);
}
/**
* @dev Sets the reward distribution. Can only be called by owner.
* @param _value The new fee value (in percentage).
*/
function setRewardSharePercent(uint256 _value) public onlyOwner whenNotPaused {
require(_value <= 1 ether, "should be less than or equal to 1 ether");
_updateUintParam(rewardSharePercentParam, _value);
emit RewardDistributionSet(_value, msg.sender);
}
/**
* @dev Sets the time from the request after which the withdrawal will be available.
* Can only be called by owner.
* @param _value The new duration value (in seconds).
*/
function setWithdrawalLockDuration(uint256 _value) public onlyOwner whenNotPaused {
require(_value <= 30 days, "shouldn't be greater than 30 days");
_updateUintParam(withdrawalLockDurationParam, _value);
emit WithdrawalLockDurationSet(_value, msg.sender);
}
/**
* @dev Sets the time during which the withdrawal will be available from the moment of unlocking.
* Can only be called by owner.
* @param _value The new duration value (in seconds).
*/
function setWithdrawalUnlockDuration(uint256 _value) public onlyOwner whenNotPaused {
require(_value >= 1 hours, "shouldn't be less than 1 hour");
_updateUintParam(withdrawalUnlockDurationParam, _value);
emit WithdrawalUnlockDurationSet(_value, msg.sender);
}
/**
* @dev Returns user total balance.
* @param voter The user who votes.
* @return Returns User total balance.
*/
function totalUserBalance(address voter)
public view
whenNotPaused
returns(uint256)
{
require(voter != address(0), "totalUserBalance: voter address is not valid");
uint256 count = lastDepositIds[voter];
uint256 totalUserStaked = 0;
for (uint i = 0; i <= count; i++) {
totalUserStaked = totalUserStaked.add(balances[voter][i]);
}
return totalUserStaked;
}
/**
* @return Returns current fee.
*/
function fee() public view whenNotPaused returns (uint256) {
return _getUintParamValue(feeParam);
}
/**
* @return Returns the current reward distribution.
*/
function rewardSharePercent() public view whenNotPaused returns (uint256) {
return _getUintParamValue(rewardSharePercentParam);
}
/**
* @return Returns current reward maturity duration in seconds.
*/
function rewardMaturityDuration() public view whenNotPaused returns (uint256) {
return _getUintParamValue(rewardMaturityDurationParam);
}
/**
* @return Returns current withdrawal lock duration.
*/
function withdrawalLockDuration() public view whenNotPaused returns (uint256) {
return _getUintParamValue(withdrawalLockDurationParam);
}
/**
* @return Returns current withdrawal unlock duration.
*/
function withdrawalUnlockDuration() public whenNotPaused view returns (uint256) {
return _getUintParamValue(withdrawalUnlockDurationParam);
}
/**
* @dev Reward _amount to be distributed proportionally to active stake.
* @param _amount New reward coming into the staking.
*/
function distribute(uint256 _amount) public whenNotPaused onlyOwner nonReentrant {
require(_amount > 0, "distribute: amount must be greater than 0");
_distribute(msg.sender, _amount, false);
}
/**
* @dev Reward _amount to be distributed proportionally to active stake.
* @param reward New reward coming into the staking.
*/
function _distribute(address sender, uint256 reward, bool isFee) internal {
emit RewardDistributed(reward);
uint256 stakersReward = reward.mul(rewardSharePercent()).div(1 ether);
uint256 onwerReward = reward.sub(stakersReward);
totalRemainingReward = totalRemainingReward.add(reward);
totalStakersReward = totalStakersReward.add(stakersReward);
totalOnwerReward = totalOnwerReward.add(onwerReward);
emit RewardUpdated(stakersReward, onwerReward, totalRemainingReward, totalStakersReward, totalOnwerReward);
if (totalStaked != 0) {
// S = S + r / T;
currentRewardFactor = currentRewardFactor.add(stakersReward.mul(1 ether).div(totalStaked));
emit RewardFactorUpdated(currentRewardFactor, totalStaked);
}
if (!isFee){
require(token.transferFrom(sender, address(this), reward), "_distribute: transfer failed");
}
}
/**
* @dev Recalculate balance in case the deposit is already made.
* @param _sender The address of the sender.
* @param _id User's unique deposit ID.
* @param _amount The amount to deposit.
*/
function _deposit(address _sender, uint256 _id, uint256 _amount) internal {
require(_amount > 0, "deposit amount should be more than 0");
uint256 userBalance = balances[_sender][_id];
uint256 deposited = 0;
uint256 reward = 0;
uint256 timePassed = 0;
// Recalculate balances
if (userBalance > 0)
{
(deposited, reward, timePassed) = _withdrawDepositAndReward(_sender, _id);
userBalance = _amount.add(deposited).add(reward);
} else {
userBalance = _amount;
}
// Assign amount
balances[_sender][_id] = userBalance;
// Update lastRewardFactor
depositRewardFactor[_sender][_id] = currentRewardFactor;
// Update total staked
totalStaked = totalStaked.add(userBalance);
// Update last deposit date
depositDates[_sender][_id] = _now();
emit Deposited(_sender, _id, _amount, userBalance, reward, timePassed, currentRewardFactor, totalStaked);
}
/**
* @dev Helper function to withdraw full amount and assign reward.
* @param _user The address of the sender.
* @param _id User's unique deposit ID.
*/
function _withdrawDepositAndReward(address _user, uint256 _id)
internal
returns (uint256 deposited, uint256 reward, uint256 timePassed) {
deposited = balances[_user][_id];
uint256 depositTime = depositDates[_user][_id];
timePassed = _now().sub(depositTime);
// Formula: reward = deposited * (S - S0[address]);
reward = deposited.mul(currentRewardFactor.sub(depositRewardFactor[_user][_id])).div(1 ether);
if (timePassed < 1 days) {
reward = 0;
} else if (timePassed < rewardMaturityDuration()) {
reward = rewardMaturityDuration().div(timePassed).mul(reward).sub(reward);
}
// Finalizing with contract states
balances[_user][_id] = 0;
totalRemainingReward = totalRemainingReward.sub(reward);
totalStaked = totalStaked.sub(deposited);
depositDates[_user][_id] = 0;
emit BeforeDepositAndRewardWithdrawn(_user, _id, deposited, reward);
}
/**
* @dev Withdraw is possible only in full amount.
* @dev Calls internal "_mint" method and then transfers tokens to the sender.
* @param _sender The address of the sender.
* @param _id User's unique deposit ID.
* @param _forced Defines whether to apply fee (true), or not (false).
*/
function _withdraw(address _sender, uint256 _id, bool _forced) internal {
require(_id > 0 && _id <= lastDepositIds[_sender], "wrong deposit id");
require(balances[_sender][_id] > 0, "insufficient funds");
(uint256 deposited, uint256 reward, uint timePassed) = _withdrawDepositAndReward(_sender, _id);
uint256 feeValue = 0;
if (_forced) {
feeValue = deposited.mul(fee()).div(1 ether);
deposited = deposited.sub(feeValue);
_distribute(_sender, feeValue, true);
}
uint256 withdrawalSum = deposited.add(reward);
require(token.transfer(_sender, withdrawalSum), "_withdraw: transfer failed");
emit Withdrawn(_sender, _id, withdrawalSum, feeValue, balances[_sender][_id], reward, timePassed, totalStaked, totalRemainingReward);
}
/**
* @dev Sets the next value of the parameter and the timestamp of this setting.
*/
function _updateUintParam(UintParam storage _param, uint256 _newValue) internal {
if (_param.timestamp == 0) {
_param.oldValue = _newValue;
} else if (_paramUpdateDelayElapsed(_param.timestamp)) {
_param.oldValue = _param.newValue;
}
_param.newValue = _newValue;
_param.timestamp = _now();
}
/**
* @return Returns the current value of the parameter.
*/
function _getUintParamValue(UintParam memory _param) internal view returns (uint256) {
return _paramUpdateDelayElapsed(_param.timestamp) ? _param.newValue : _param.oldValue;
}
/**
* @return Returns true if param update delay elapsed.
*/
function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) {
return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY);
}
/**
* @dev Pauses all actions on the contract.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*/
function pause() public onlyOwner virtual {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
*/
function unpause() public onlyOwner virtual {
_unpause();
}
/**
* @return Returns current timestamp.
*/
function _now() internal view returns (uint256) {
// Note that the timestamp can have a 900-second error:
// https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md
return block.timestamp; // solium-disable-line security/no-block-members
}
} | return Returns current withdrawal unlock duration./ | function withdrawalUnlockDuration() public whenNotPaused view returns (uint256) {
return _getUintParamValue(withdrawalUnlockDurationParam);
}
| 433,298 |
./full_match/122/0xCbc6Ce8C3bc4E5D7EB0fe7440B7b0f58C2884D3B/sources/contracts/LiquidStakingPool.sol | Returns the treasury address/ | function getTreasury() public view returns (address) {
return _treasury;
}
| 16,366,548 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Decimal
* @notice Library that defines a fixed-point number with 18 decimal places.
*
* audit-info: Extended from dYdX's Decimal library:
* https://github.com/dydxprotocol/solo/blob/master/contracts/protocol/lib/Decimal.sol
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
/**
* @notice Fixed-point base for Decimal.D256 values
*/
uint256 constant BASE = 10**18;
// ============ Structs ============
/**
* @notice Main struct to hold Decimal.D256 state
* @dev Represents the number value / BASE
*/
struct D256 {
/**
* @notice Underlying value of the Decimal.D256
*/
uint256 value;
}
// ============ Static Functions ============
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 0.0
* @return Decimal.D256 representation of 0.0
*/
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 1.0
* @return Decimal.D256 representation of 1.0
*/
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a`
* @param a Integer to transform to Decimal.D256 type
* @return Decimal.D256 representation of integer`a`
*/
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a` / `b`
* @param a Numerator of ratio to transform to Decimal.D256 type
* @param b Denominator of ratio to transform to Decimal.D256 type
* @return Decimal.D256 representation of ratio `a` / `b`
*/
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
/**
* @notice Adds integer `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
uint256 amount = b.mul(BASE);
return D256({ value: self.value > amount ? self.value.sub(amount) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b, reason) });
}
/**
* @notice Exponentiates Decimal.D256 `self` to the power of integer `b`
* @dev Not optimized - is only suitable to use with small exponents
* @param self Original Decimal.D256 number
* @param b Integer exponent
* @return Resulting Decimal.D256
*/
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
/**
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value > b.value ? self.value.sub(b.value) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value, reason) });
}
/**
* @notice Checks if `b` is equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is equal to `self`
*/
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
/**
* @notice Checks if `b` is greater than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than `self`
*/
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
/**
* @notice Checks if `b` is less than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than `self`
*/
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
/**
* @notice Checks if `b` is greater than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than or equal to `self`
*/
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
/**
* @notice Checks if `b` is less than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than or equal to `self`
*/
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
/**
* @notice Checks if `self` is equal to 0
* @param self Original Decimal.D256 number
* @return Whether `self` is equal to 0
*/
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
/**
* @notice Truncates the decimal part of `self` and returns the integer value as a uint256
* @param self Original Decimal.D256 number
* @return Truncated Integer value as a uint256
*/
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ General Math ============
/**
* @notice Determines the minimum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting minimum Decimal.D256
*/
function min(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return lessThan(a, b) ? a : b;
}
/**
* @notice Determines the maximum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting maximum Decimal.D256
*/
function max(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return greaterThan(a, b) ? a : b;
}
// ============ Core Methods ============
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* Reverts on divide-by-zero with reason `reason`
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @param reason Revert reason
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator,
string memory reason
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator, reason);
}
/**
* @notice Compares Decimal.D256 `a` to Decimal.D256 `b`
* @dev Internal only - helper
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return 0 if a < b, 1 if a == b, 2 if a > b
*/
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title IManagedToken
* @notice Generic interface for ERC20 tokens that can be minted and burned by their owner
* @dev Used by Dollar and Stake in this protocol
*/
interface IManagedToken {
/**
* @notice Mints `amount` tokens to the {owner}
* @param amount Amount of token to mint
*/
function burn(uint256 amount) external;
/**
* @notice Burns `amount` tokens from the {owner}
* @param amount Amount of token to burn
*/
function mint(uint256 amount) external;
}
/**
* @title IGovToken
* @notice Generic interface for ERC20 tokens that have Compound-governance features
* @dev Used by Stake and other compatible reserve-held tokens
*/
interface IGovToken {
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external;
}
/**
* @title IReserve
* @notice Interface for the protocol reserve
*/
interface IReserve {
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* @return Current ESD redemption price
*/
function redeemPrice() external view returns (Decimal.D256 memory);
}
interface IRegistry {
/**
* @notice USDC token contract
*/
function usdc() external view returns (address);
/**
* @notice Compound protocol cUSDC pool
*/
function cUsdc() external view returns (address);
/**
* @notice ESD stablecoin contract
*/
function dollar() external view returns (address);
/**
* @notice ESDS governance token contract
*/
function stake() external view returns (address);
/**
* @notice ESD reserve contract
*/
function reserve() external view returns (address);
/**
* @notice ESD governor contract
*/
function governor() external view returns (address);
/**
* @notice ESD timelock contract, owner for the protocol
*/
function timelock() external view returns (address);
/**
* @notice Migration contract to bride v1 assets with current system
*/
function migrator() external view returns (address);
/**
* @notice Registers a new address for USDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setUsdc(address newValue) external;
/**
* @notice Registers a new address for cUSDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setCUsdc(address newValue) external;
/**
* @notice Registers a new address for ESD
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setDollar(address newValue) external;
/**
* @notice Registers a new address for ESDS
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setStake(address newValue) external;
/**
* @notice Registers a new address for the reserve
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setReserve(address newValue) external;
/**
* @notice Registers a new address for the governor
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setGovernor(address newValue) external;
/**
* @notice Registers a new address for the timelock
* @dev Owner only - governance hook
* Does not automatically update the owner of all owned protocol contracts
* @param newValue New address to register
*/
function setTimelock(address newValue) external;
/**
* @notice Registers a new address for the v1 migration contract
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setMigrator(address newValue) external;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title TimeUtils
* @notice Library that accompanies Decimal to convert unix time into Decimal.D256 values
*/
library TimeUtils {
/**
* @notice Number of seconds in a single day
*/
uint256 private constant SECONDS_IN_DAY = 86400;
/**
* @notice Converts an integer number of seconds to a Decimal.D256 amount of days
* @param s Number of seconds to convert
* @return Equivalent amount of days as a Decimal.D256
*/
function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Implementation
* @notice Common functions and accessors across upgradeable, ownable contracts
*/
contract Implementation {
/**
* @notice Emitted when {owner} is updated with `newOwner`
*/
event OwnerUpdate(address newOwner);
/**
* @notice Emitted when {registry} is updated with `newRegistry`
*/
event RegistryUpdate(address newRegistry);
/**
* @dev Storage slot with the address of the current implementation
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Storage slot with the admin of the contract
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
*/
bytes32 private constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant OWNER_SLOT = keccak256("emptyset.v2.implementation.owner");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant REGISTRY_SLOT = keccak256("emptyset.v2.implementation.registry");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant NOT_ENTERED_SLOT = keccak256("emptyset.v2.implementation.notEntered");
// UPGRADEABILITY
/**
* @notice Returns the current implementation
* @return Address of the current implementation
*/
function implementation() external view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @notice Returns the current proxy admin contract
* @return Address of the current proxy admin contract
*/
function admin() external view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
// REGISTRY
/**
* @notice Updates the registry contract
* @dev Owner only - governance hook
* If registry is already set, the new registry's timelock must match the current's
* @param newRegistry New registry contract
*/
function setRegistry(address newRegistry) external onlyOwner {
IRegistry registry = registry();
// New registry must have identical owner
require(newRegistry != address(0), "Implementation: zero address");
require(
(address(registry) == address(0) && Address.isContract(newRegistry)) ||
IRegistry(newRegistry).timelock() == registry.timelock(),
"Implementation: timelocks must match"
);
_setRegistry(newRegistry);
emit RegistryUpdate(newRegistry);
}
/**
* @notice Updates the registry contract
* @dev Internal only
* @param newRegistry New registry contract
*/
function _setRegistry(address newRegistry) internal {
bytes32 position = REGISTRY_SLOT;
assembly {
sstore(position, newRegistry)
}
}
/**
* @notice Returns the current registry contract
* @return Address of the current registry contract
*/
function registry() public view returns (IRegistry reg) {
bytes32 slot = REGISTRY_SLOT;
assembly {
reg := sload(slot)
}
}
// OWNER
/**
* @notice Takes ownership over a contract if none has been set yet
* @dev Needs to be called initialize ownership after deployment
* Ensure that this has been properly set before using the protocol
*/
function takeOwnership() external {
require(owner() == address(0), "Implementation: already initialized");
_setOwner(msg.sender);
emit OwnerUpdate(msg.sender);
}
/**
* @notice Updates the owner contract
* @dev Owner only - governance hook
* @param newOwner New owner contract
*/
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(this), "Implementation: this");
require(Address.isContract(newOwner), "Implementation: not contract");
_setOwner(newOwner);
emit OwnerUpdate(newOwner);
}
/**
* @notice Updates the owner contract
* @dev Internal only
* @param newOwner New owner contract
*/
function _setOwner(address newOwner) internal {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
/**
* @notice Owner contract with admin permission over this contract
* @return Owner contract
*/
function owner() public view returns (address o) {
bytes32 slot = OWNER_SLOT;
assembly {
o := sload(slot)
}
}
/**
* @dev Only allow when the caller is the owner address
*/
modifier onlyOwner {
require(msg.sender == owner(), "Implementation: not owner");
_;
}
// NON REENTRANT
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(notEntered(), "Implementation: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(true);
}
/**
* @notice The entered status of the current call
* @return entered status
*/
function notEntered() internal view returns (bool ne) {
bytes32 slot = NOT_ENTERED_SLOT;
assembly {
ne := sload(slot)
}
}
/**
* @notice Updates the entered status of the current call
* @dev Internal only
* @param newNotEntered New entered status
*/
function _setNotEntered(bool newNotEntered) internal {
bytes32 position = NOT_ENTERED_SLOT;
assembly {
sstore(position, newNotEntered)
}
}
// SETUP
/**
* @notice Hook to surface arbitrary logic to be called after deployment by owner
* @dev Governance hook
* Does not ensure that it is only called once because it is permissioned to governance only
*/
function setup() external onlyOwner {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_setNotEntered(true);
_setup();
}
/**
* @notice Override to provide addition setup logic per implementation
*/
function _setup() internal { }
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveTypes
* @notice Contains all reserve state structs
*/
contract ReserveTypes {
/**
* @notice Stores state for a single order
*/
struct Order {
/**
* @notice price (takerAmount per makerAmount) for the order as a Decimal
*/
Decimal.D256 price;
/**
* @notice total available amount of the maker token
*/
uint256 amount;
}
/**
* @notice Stores state for the entire reserve
*/
struct State {
/**
* @notice Total debt
*/
uint256 totalDebt;
/**
* @notice Mapping of total debt per borrower
*/
mapping(address => uint256) debt;
/**
* @notice Mapping of all registered limit orders
*/
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
/**
* @title ReserveState
* @notice Reserve state
*/
contract ReserveState {
/**
* @notice Entirety of the reserve contract state
* @dev To upgrade state, append additional state variables at the end of this contract
*/
ReserveTypes.State internal _state;
}
/**
* @title ReserveAccessors
* @notice Reserve state accessor helpers
*/
contract ReserveAccessors is Implementation, ReserveState {
using SafeMath for uint256;
using Decimal for Decimal.D256;
// SWAPPER
/**
* @notice Full state of the `makerToken`-`takerToken` order
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @return Specified order
*/
function order(address makerToken, address takerToken) public view returns (ReserveTypes.Order memory) {
return _state.orders[makerToken][takerToken];
}
/**
* @notice Returns the total debt outstanding
* @return Total debt
*/
function totalDebt() public view returns (uint256) {
return _state.totalDebt;
}
/**
* @notice Returns the total debt outstanding for `borrower`
* @return Total debt for borrower
*/
function debt(address borrower) public view returns (uint256) {
return _state.debt[borrower];
}
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Internal only
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount to decrement in ESD
*/
function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
/**
* @notice Decrements the available amount of the specified `makerToken`-`takerToken` order
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param amount Amount to decrement in ESD
* @param reason revert reason
*/
function _decrementOrderAmount(address makerToken, address takerToken, uint256 amount, string memory reason) internal {
_state.orders[makerToken][takerToken].amount = _state.orders[makerToken][takerToken].amount.sub(amount, reason);
}
/**
* @notice Decrements the debt for `borrower`
* @dev Internal only
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
*/
function _incrementDebt(address borrower, uint256 amount) internal {
_state.totalDebt = _state.totalDebt.add(amount);
_state.debt[borrower] = _state.debt[borrower].add(amount);
}
/**
* @notice Increments the debt for `borrower`
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
* @param reason revert reason
*/
function _decrementDebt(address borrower, uint256 amount, string memory reason) internal {
_state.totalDebt = _state.totalDebt.sub(amount, reason);
_state.debt[borrower] = _state.debt[borrower].sub(amount, reason);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveVault
* @notice Logic to passively manage USDC reserve with low-risk strategies
* @dev Currently uses Compound to lend idle USDC in the reserve
*/
contract ReserveVault is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
/**
* @notice Emitted when `amount` USDC is supplied to the vault
*/
event SupplyVault(uint256 amount);
/**
* @notice Emitted when `amount` USDC is redeemed from the vault
*/
event RedeemVault(uint256 amount);
/**
* @notice Total value of the assets managed by the vault
* @dev Denominated in USDC
* @return Total value of the vault
*/
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
Decimal.D256 memory exchangeRate = Decimal.D256({value: cUsdc.exchangeRateStored()});
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
/**
* @notice Supplies `amount` USDC to the external protocol for reward accrual
* @dev Supplies to the Compound USDC lending pool
* @param amount Amount of USDC to supply
*/
function _supplyVault(uint256 amount) internal {
address cUsdc = registry().cUsdc();
IERC20(registry().usdc()).safeApprove(cUsdc, amount);
require(ICErc20(cUsdc).mint(amount) == 0, "ReserveVault: supply failed");
emit SupplyVault(amount);
}
/**
* @notice Redeems `amount` USDC from the external protocol for reward accrual
* @dev Redeems from the Compound USDC lending pool
* @param amount Amount of USDC to redeem
*/
function _redeemVault(uint256 amount) internal {
require(ICErc20(registry().cUsdc()).redeemUnderlying(amount) == 0, "ReserveVault: redeem failed");
emit RedeemVault(amount);
}
/**
* @notice Claims all available governance rewards from the external protocol
* @dev Owner only - governance hook
* Claims COMP accrued from lending on the USDC pool
*/
function claimVault() external onlyOwner {
ICErc20(registry().cUsdc()).comptroller().claimComp(address(this));
}
/**
* @notice Delegates voting power to `delegatee` for `token` governance token held by the reserve
* @dev Owner only - governance hook
* Works for all COMP-based governance tokens
* @param token Governance token to delegate voting power
* @param delegatee Account to receive reserve's voting power
*/
function delegateVault(address token, address delegatee) external onlyOwner {
IGovToken(token).delegate(delegatee);
}
}
/**
* @title ICErc20
* @dev Compound ICErc20 interface
*/
contract ICErc20 {
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint256);
/**
* @notice Get the token balance of the `account`
* @param account The address of the account to query
* @return The number of tokens owned by `account`
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Contract which oversees inter-cToken operations
*/
function comptroller() public view returns (IComptroller);
}
/**
* @title IComptroller
* @dev Compound IComptroller interface
*/
contract IComptroller {
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveComptroller
* @notice Reserve accounting logic for managing the ESD stablecoin.
*/
contract ReserveComptroller is ReserveAccessors, ReserveVault {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC
*/
event Mint(address indexed account, uint256 mintAmount, uint256 costAmount);
/**
* @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC
*/
event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount);
/**
* @notice Emitted when `account` borrows `borrowAmount` ESD from the reserve
*/
event Borrow(address indexed account, uint256 borrowAmount);
/**
* @notice Emitted when `account` repays `repayAmount` ESD to the reserve
*/
event Repay(address indexed account, uint256 repayAmount);
/**
* @notice Helper constant to convert ESD to USDC and vice versa
*/
uint256 private constant USDC_DECIMAL_DIFF = 1e12;
// EXTERNAL
/**
* @notice The total value of the reserve-owned assets denominated in USDC
* @return Reserve total value
*/
function reserveBalance() public view returns (uint256) {
uint256 internalBalance = _balanceOf(registry().usdc(), address(this));
uint256 vaultBalance = _balanceOfVault();
return internalBalance.add(vaultBalance);
}
/**
* @notice The ratio of the {reserveBalance} to total ESD issuance
* @dev Assumes 1 ESD = 1 USDC, normalizing for decimals
* @return Reserve ratio
*/
function reserveRatio() public view returns (Decimal.D256 memory) {
uint256 issuance = _totalSupply(registry().dollar()).sub(totalDebt());
return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance);
}
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* Equivalent to the current reserve ratio less the current redemption tax (if any)
* @return Current ESD redemption price
*/
function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
/**
* @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer USDC
* @param amount Amount of ESD to mint
*/
function mint(uint256 amount) external nonReentrant {
uint256 costAmount = _toUsdcAmount(amount);
// Take the ceiling to ensure no "free" ESD is minted
costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1);
_transferFrom(registry().usdc(), msg.sender, address(this), costAmount);
_supplyVault(costAmount);
_mintDollar(msg.sender, amount);
emit Mint(msg.sender, amount, costAmount);
}
/**
* @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice}
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer ESD
* @param amount Amount of ESD to mint
*/
function redeem(uint256 amount) external nonReentrant {
uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256());
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
_redeemVault(redeemAmount);
_transfer(registry().usdc(), msg.sender, redeemAmount);
emit Redeem(msg.sender, amount, redeemAmount);
}
/**
* @notice Lends `amount` ESD to `to` while recording the corresponding debt entry
* @dev Non-reentrant
* Caller must be owner
* Used to pre-fund trusted contracts with ESD without backing (e.g. batchers)
* @param account Address to send the borrowed ESD to
* @param amount Amount of ESD to borrow
*/
function borrow(address account, uint256 amount) external onlyOwner nonReentrant {
require(_canBorrow(account, amount), "ReserveComptroller: cant borrow");
_incrementDebt(account, amount);
_mintDollar(account, amount);
emit Borrow(account, amount);
}
/**
* @notice Repays `amount` ESD on behalf of `to` while reducing its corresponding debt
* @dev Non-reentrant
* @param account Address to repay ESD on behalf of
* @param amount Amount of ESD to repay
*/
function repay(address account, uint256 amount) external nonReentrant {
_decrementDebt(account, amount, "ReserveComptroller: insufficient debt");
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
emit Repay(account, amount);
}
// INTERNAL
/**
* @notice Mints `amount` ESD to `account`
* @dev Internal only
* @param account Account to receive minted ESD
* @param amount Amount of ESD to mint
*/
function _mintDollar(address account, uint256 amount) internal {
address dollar = registry().dollar();
IManagedToken(dollar).mint(amount);
IERC20(dollar).safeTransfer(account, amount);
}
/**
* @notice Burns `amount` ESD held by the reserve
* @dev Internal only
* @param amount Amount of ESD to burn
*/
function _burnDollar(uint256 amount) internal {
IManagedToken(registry().dollar()).burn(amount);
}
/**
* @notice `token` balance of `account`
* @dev Internal only
* @param token Token to get the balance for
* @param account Account to get the balance of
*/
function _balanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account);
}
/**
* @notice Total supply of `token`
* @dev Internal only
* @param token Token to get the total supply of
*/
function _totalSupply(address token) internal view returns (uint256) {
return IERC20(token).totalSupply();
}
/**
* @notice Safely transfers `amount` `token` from the caller to `receiver`
* @dev Internal only
* @param token Token to transfer
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transfer(address token, address receiver, uint256 amount) internal {
IERC20(token).safeTransfer(receiver, amount);
}
/**
* @notice Safely transfers `amount` `token` from the `sender` to `receiver`
* @dev Internal only
Requires `amount` allowance from `sender` for caller
* @param token Token to transfer
* @param sender Account to send the tokens
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {
IERC20(token).safeTransferFrom(sender, receiver, amount);
}
/**
* @notice Converts ESD amount to USDC amount
* @dev Private only
* Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount
* @param dec18Amount 18-decimal ERC20 amount
* @return 6-decimals ERC20 amount
*/
function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) {
return dec18Amount.div(USDC_DECIMAL_DIFF);
}
/**
* @notice Convert USDC amount to ESD amount
* @dev Private only
* Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount
* @param usdcAmount 6-decimal ERC20 amount
* @return 18-decimals ERC20 amount
*/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) {
return usdcAmount.mul(USDC_DECIMAL_DIFF);
}
function _canBorrow(address account, uint256 amount) private view returns (bool) {
uint256 totalBorrowAmount = debt(account).add(amount);
if ( // WrapOnlyBatcher
account == address(0x0B663CeaCEF01f2f88EB7451C70Aa069f19dB997) &&
totalBorrowAmount <= 1_000_000e18
) return true;
return false;
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveSwapper
* @notice Logic for managing outstanding reserve limit orders.
* Since the reserve is autonomous, it cannot use traditional DEXs without being front-run. The `ReserveSwapper`
* allows governance to place outstanding limit orders selling reserve assets in exchange for assets the reserve
* wishes to purchase. This is the main mechanism by which the reserve may diversify itself, or buy back ESDS
* using generated rewards.
*/
contract ReserveSwapper is ReserveComptroller {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `amount` of the `makerToken`-`takerToken` order is registered with price `price`
*/
event OrderRegistered(address indexed makerToken, address indexed takerToken, uint256 price, uint256 amount);
/**
* @notice Emitted when the reserve pays `takerAmount` of `takerToken` in exchange for `makerAmount` of `makerToken`
*/
event Swap(address indexed makerToken, address indexed takerToken, uint256 takerAmount, uint256 makerAmount);
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Owner only - governance hook
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount of the makerToken that reserve wishes to sell - uint256(-1) indicates all reserve funds
*/
function registerOrder(address makerToken, address takerToken, uint256 price, uint256 amount) external onlyOwner {
_updateOrder(makerToken, takerToken, price, amount);
emit OrderRegistered(makerToken, takerToken, price, amount);
}
/**
* @notice Purchases `makerToken` from the reserve in exchange for `takerAmount` of `takerToken`
* @dev Non-reentrant
* Uses the state-defined price for the `makerToken`-`takerToken` order
* Maker and taker tokens must be different
* Cannot swap ESD
* @param makerToken Token that the caller wishes to buy
* @param takerToken Token that the caller wishes to sell
* @param takerAmount Amount of takerToken to sell
*/
function swap(address makerToken, address takerToken, uint256 takerAmount) external nonReentrant {
address dollar = registry().dollar();
require(makerToken != dollar, "ReserveSwapper: unsupported token");
require(takerToken != dollar, "ReserveSwapper: unsupported token");
require(makerToken != takerToken, "ReserveSwapper: tokens equal");
ReserveTypes.Order memory order = order(makerToken, takerToken);
uint256 makerAmount = Decimal.from(takerAmount).div(order.price, "ReserveSwapper: no order").asUint256();
if (order.amount != uint256(-1))
_decrementOrderAmount(makerToken, takerToken, makerAmount, "ReserveSwapper: insufficient amount");
_transferFrom(takerToken, msg.sender, address(this), takerAmount);
_transfer(makerToken, msg.sender, makerAmount);
emit Swap(makerToken, takerToken, takerAmount, makerAmount);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveImpl
* @notice Top-level Reserve contract that extends all other reserve sub-contracts
* @dev This contract should be used an implementation contract for an AdminUpgradeabilityProxy
*/
contract ReserveImpl is IReserve, ReserveComptroller, ReserveIssuer, ReserveSwapper { } | Number of seconds in a single day/ Converts an integer number of seconds to a Decimal.D256 amount of days s Number of seconds to convert return Equivalent amount of days as a Decimal.D256/ | function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
| 12,066,189 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
contract Dominapes is ERC721 {
event Mint(address indexed from, uint256 indexed tokenId);
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
modifier saleStarted() {
require(
startMintDate != 0 && startMintDate <= block.timestamp,
"You are too early"
);
_;
}
uint256 public startMintDate = 1628636400;
uint256 private salePrice = 15000000000000000;
uint256 private totalTokens = 8000;
uint256 private totalMintedTokens = 0;
uint256 private maxSlicesPerWallet = 200;
uint256 private maxSlicesPerTransaction = 10;
string private baseURI =
"https://dominapes.s3.us-west-1.amazonaws.com/";
bool public premintingComplete = false;
uint256 public giveawayCount = 50;
mapping(address => uint256) private claimedSlicesPerWallet;
uint16[] availableSlices;
constructor() ERC721("Dominapes", "DPE") {
addAvailableSlices();
premintSlices();
}
// ONLY OWNER
/**
* @dev Allows to withdraw the Ether in the contract
*/
function withdraw() external onlyOwner {
uint256 totalBalance = address(this).balance;
payable(msg.sender).transfer(totalBalance);
}
/**
* @dev Sets the base URI for the API that provides the NFT data.
*/
function setBaseTokenURI(string memory _uri) external onlyOwner {
baseURI = _uri;
}
/**
* @dev Sets the claim price for each slice
*/
function setsalePrice(uint256 _salePrice) external onlyOwner {
salePrice = _salePrice;
}
/**
* @dev Populates the available slices
*/
function addAvailableSlices()
internal
onlyOwner
{
for (uint16 i = 0; i <= 7999; i++) {
availableSlices.push(i);
}
}
/**
* @dev Removes a chosen slice from the available list
*/
function removeSlicesFromAvailableSlices(uint16 tokenId)
external
onlyOwner
{
for (uint16 i; i <= availableSlices.length; i++) {
if (availableSlices[i] != tokenId) {
continue;
}
availableSlices[i] = availableSlices[availableSlices.length - 1];
availableSlices.pop();
break;
}
}
/**
* @dev Allow devs to hand pick some slices before the available slices list is created
*/
function allocateTokens(uint256[] memory tokenIds)
external
onlyOwner
{
require(availableSlices.length == 0, "Available slices are already set");
_batchMint(msg.sender, tokenIds);
totalMintedTokens += tokenIds.length;
}
/**
* @dev Sets the date that users can start claiming slices
*/
function setStartSaleDate(uint256 _startSaleDate)
external
onlyOwner
{
startMintDate = _startSaleDate;
}
/**
* @dev Sets the date that users can start minting slices
*/
function setStartMintDate(uint256 _startMintDate)
external
onlyOwner
{
startMintDate = _startMintDate;
}
/**
* @dev Checks if an slice is in the available list
*/
function isSliceAvailable(uint16 tokenId)
external
view
onlyOwner
returns (bool)
{
for (uint16 i; i < availableSlices.length; i++) {
if (availableSlices[i] == tokenId) {
return true;
}
}
return false;
}
/**
* @dev Give random slices to the provided addresses
*/
function ownerMintSlices(address[] memory addresses)
external
onlyOwner
{
require(
availableSlices.length >= addresses.length,
"No slices left to be claimed"
);
totalMintedTokens += addresses.length;
for (uint256 i; i < addresses.length; i++) {
_mint(addresses[i], getSliceToBeClaimed());
}
}
/**
* @dev Give random slices to the provided address
*/
function premintSlices()
internal
onlyOwner
{
require(availableSlices.length >= giveawayCount, "No slices left to be claimed");
require(
!premintingComplete,
"You can only premint the horses once"
);
totalMintedTokens += giveawayCount;
uint256[] memory tokenIds = new uint256[](giveawayCount);
for (uint256 i; i < giveawayCount; i++) {
tokenIds[i] = getSliceToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
premintingComplete = true;
}
// END ONLY OWNER
/**
* @dev Claim a single slice
*/
function mintSlice() external payable callerIsUser saleStarted {
require(msg.value >= salePrice, "Not enough Ether to claim an slice");
require(
claimedSlicesPerWallet[msg.sender] < maxSlicesPerWallet,
"You cannot claim more slices"
);
require(availableSlices.length > 0, "No slices left to be claimed");
claimedSlicesPerWallet[msg.sender]++;
totalMintedTokens++;
_mint(msg.sender, getSliceToBeClaimed());
}
/**
* @dev Claim up to 10 slices at once
*/
function mintSlices(uint256 amount)
external
payable
callerIsUser
saleStarted
{
require(
msg.value >= salePrice * amount,
"Not enough Ether to claim the slices"
);
require(
claimedSlicesPerWallet[msg.sender] + amount <= maxSlicesPerWallet,
"You cannot claim more slices"
);
require(amount <= maxSlicesPerTransaction, "You can only claim 10 slices in 1 transaction");
require(availableSlices.length >= amount, "No slices left to be claimed");
uint256[] memory tokenIds = new uint256[](amount);
claimedSlicesPerWallet[msg.sender] += amount;
totalMintedTokens += amount;
for (uint256 i; i < amount; i++) {
tokenIds[i] = getSliceToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
}
/**
* @dev Returns the tokenId by index
*/
function tokenByIndex(uint256 tokenId) external view returns (uint256) {
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
return tokenId;
}
/**
* @dev Returns the base URI for the tokens API.
*/
function baseTokenURI() external view returns (string memory) {
return baseURI;
}
/**
* @dev Returns how many slices are still available to be claimed
*/
function getAvailableSlices() external view returns (uint256) {
return availableSlices.length;
}
/**
* @dev Returns the claim price
*/
function getSalePrice() external view returns (uint256) {
return salePrice;
}
/**
* @dev Returns the total supply
*/
function totalSupply() external view virtual returns (uint256) {
return totalMintedTokens;
}
// Private and Internal functions
/**
* @dev Returns a random available slice to be claimed
*/
function getSliceToBeClaimed() private returns (uint256) {
uint256 random = _getRandomNumber(availableSlices.length);
uint256 tokenId = uint256(availableSlices[random]);
availableSlices[random] = availableSlices[availableSlices.length - 1];
availableSlices.pop();
return tokenId;
}
/**
* @dev Generates a pseudo-random number.
*/
function _getRandomNumber(uint256 _upper) private view returns (uint256) {
uint256 random = uint256(
keccak256(
abi.encodePacked(
availableSlices.length,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender
)
)
);
return random % _upper;
}
/**
* @dev See {ERC721}.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mulScale(
uint256 x,
uint256 y,
uint128 scale
) internal pure returns (uint256) {
uint256 a = x / scale;
uint256 b = x % scale;
uint256 c = y / scale;
uint256 d = y % scale;
return a * c * scale + a * d + b * c + (b * d) / scale;
}
} | Checks if an slice is in the available list/ | function isSliceAvailable(uint16 tokenId)
external
view
onlyOwner
returns (bool)
{
for (uint16 i; i < availableSlices.length; i++) {
if (availableSlices[i] == tokenId) {
return true;
}
}
return false;
}
| 13,740,921 |
/**
*Submitted for verification at Etherscan.io on 2022-03-17
*/
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// 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/Stake.sol
pragma solidity ^0.8.0;
contract Stake is Ownable {
struct sStake {
uint256 total_rewards_unclaimed;
uint256 total_rewards_claimed;
uint256 total_staked;
uint256 rewards_claimed_at;
uint256 stake_started_at;
}
// Stakes
mapping(address => sStake) public stakes;
// Refers
mapping(address => address) public refers;
// total staked
uint256 public totalStaked = 0;
// minimum value to stake
uint256 public minValueToStake = 0.01 ether;
// maximum value to stake
uint256 public maxValueToStake = 1 ether;
// Yield multiply by 10000
uint256 public yield = 110;
// Maximum Claim Rewards
uint256 public maximumClaimRewardsPorcentage = 3;
// Refer Porcentage
uint256 public referPorcentage = 10;
function setMinValueToStake(uint256 _value) public onlyOwner {
minValueToStake = _value;
}
function setMaxValueToStake(uint256 _value) public onlyOwner {
maxValueToStake = _value;
}
function setYield(uint256 _value) public onlyOwner {
yield = _value;
}
function setMaximumClaimRewardsPorcentage(uint256 _value) public onlyOwner {
maximumClaimRewardsPorcentage = _value;
}
function setReferPorcentage(uint256 _value) public onlyOwner {
referPorcentage = _value;
}
function stake(address _address, address _refer) public payable {
require(minValueToStake <= msg.value, "Value not enoght!");
require(maxValueToStake >= (msg.value + stakes[_address].total_staked), "Maximum of stake exceeded!");
require(_address != _refer, "Address and Refer can not be equal!");
_stake(_address, msg.value);
// Set refer address
if(refers[_address] == address(0x0)){
refers[_address] = _refer;
}else{
_refer = refers[_address];
}
// Indication to refer
if(referPorcentage > 0 && stakes[_refer].total_staked > 0){
_stake(_refer, msg.value / referPorcentage);
}
}
function _stake(address _address, uint256 _value) internal {
// Update the actual rewards unclaimed
if(stakes[_address].total_staked > 0){
updateAndGetTotalRewardsUnclaimed(_address);
}
totalStaked += _value;
stakes[_address].total_staked += _value;
stakes[_address].stake_started_at = block.timestamp;
emit StartStake(_address, msg.value);
}
function claimRewards(address payable _address) public payable{
// Get rewards unclaimed
uint256 _total_rewards_unclaimed = updateAndGetTotalRewardsUnclaimed(_address);
require(address(this).balance > _total_rewards_unclaimed, "Balance of contract not enoght!");
if(_total_rewards_unclaimed > 0){
//Update total rewards unclaimed
stakes[_address].total_rewards_unclaimed = 0;
// Update total rewards claimed
stakes[_address].total_rewards_claimed += _total_rewards_unclaimed;
// If Stake is Over
if(stakes[_address].total_rewards_claimed >= getMaximumClaimRewardsTotal(_address)){
uint256 _total_rewards_claimed = stakes[_address].total_rewards_claimed;
// Remove of total staked
totalStaked -= stakes[_address].total_staked;
// Reset All Stake Data
stakes[_address].total_rewards_claimed = 0;
stakes[_address].total_staked = 0;
stakes[_address].rewards_claimed_at = 0;
stakes[_address].stake_started_at = 0;
emit StopStake(_address, _total_rewards_claimed);
}
_address.transfer(_total_rewards_unclaimed);
emit ClaimRewards(_address, _total_rewards_unclaimed);
}
}
function updateAndGetTotalRewardsUnclaimed(address _address) public returns(uint256){
//Update total rewards unclaimed
stakes[_address].total_rewards_unclaimed = getTotalRewardsUnclaimed(_address);
//Update reward claimed at
stakes[_address].rewards_claimed_at = block.timestamp;
//Return total rewards unclaimed
return stakes[_address].total_rewards_unclaimed;
}
function getTotalRewardsUnclaimed(address _address) public view returns(uint256){
// Set total rewards unclaimed
uint256 totalRewardsUnclaimed = stakes[_address].total_rewards_unclaimed + calculeStakeBalance(_address);
// Set the maximum Claim Rewards Total
uint256 maximumClaimRewardsTotal = getMaximumClaimRewardsTotal(_address);
// Check the maximum of Rewards
if((totalRewardsUnclaimed + stakes[_address].total_rewards_claimed) > maximumClaimRewardsTotal) {
totalRewardsUnclaimed -= (totalRewardsUnclaimed + stakes[_address].total_rewards_claimed) - maximumClaimRewardsTotal;
}
// Filter to 0
if(totalRewardsUnclaimed < 0){
totalRewardsUnclaimed = 0;
}
return totalRewardsUnclaimed;
}
function getMaximumClaimRewardsTotal(address _address) public view returns(uint256){
uint256 maximumClaimRewardsTotal;
// Set the maximum Claim Rewards Total
maximumClaimRewardsTotal = (maximumClaimRewardsPorcentage*stakes[_address].total_staked);
return maximumClaimRewardsTotal;
}
function calculeStakeBalance(address _address) public view returns(uint256){
uint256 totalReward;
uint256 timeStakingBySeconds;
uint256 actualTime;
actualTime = block.timestamp;
timeStakingBySeconds = 0;
// Calculate total brains staked
if(stakes[_address].rewards_claimed_at > 0){
timeStakingBySeconds = actualTime - stakes[_address].rewards_claimed_at;
}else{
timeStakingBySeconds = actualTime - stakes[_address].stake_started_at;
}
totalReward = (yield * stakes[_address].total_staked * timeStakingBySeconds) / 864000000;
// Filter to 0
if(totalReward < 0){
totalReward = 0;
}
return totalReward;
}
function withdraw(uint256 amount) public onlyOwner {
require(amount <= address(this).balance, "Amount should be equal or lower of balance.");
payable(msg.sender).transfer(amount);
}
/*
* Event
*/
event StartStake(address _address, uint256 value);
event StopStake(address _address, uint256 value);
event ClaimRewards(address _address, uint256 value);
} | Set total rewards unclaimed Set the maximum Claim Rewards Total Check the maximum of Rewards Filter to 0 | function getTotalRewardsUnclaimed(address _address) public view returns(uint256){
uint256 totalRewardsUnclaimed = stakes[_address].total_rewards_unclaimed + calculeStakeBalance(_address);
uint256 maximumClaimRewardsTotal = getMaximumClaimRewardsTotal(_address);
if((totalRewardsUnclaimed + stakes[_address].total_rewards_claimed) > maximumClaimRewardsTotal) {
totalRewardsUnclaimed -= (totalRewardsUnclaimed + stakes[_address].total_rewards_claimed) - maximumClaimRewardsTotal;
}
if(totalRewardsUnclaimed < 0){
totalRewardsUnclaimed = 0;
}
return totalRewardsUnclaimed;
}
| 6,782,975 |
./full_match/137/0x1d92809eca5A7584c38D7620a19F7D9469a75699/sources/DAO/ETHTIMEbonddepositry.sol | calculate current bond price and remove floor if above return price_ uint/ | function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ) / 1e7;
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
terms.minimumPrice = 0;
}
} else if ( terms.minimumPrice != 0 ) {
}
| 4,782,852 |
./full_match/1/0xf3B4215cDbA99d4564C42b143593BA59535b507b/sources/contracts/HalloweenDorkis.sol | Set the base token URI/ | function setBaseTokenURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
| 3,858,048 |
./full_match/1/0xF647f29860335E064fAc9f1Fe28BC8C9fd5331b0/sources/contracts/Phase3_OnChainMfers.sol | update claim price, will attempt to always keep claim price at ~$69 USD | function updateClaimPrice(uint256 _newPrice) external onlyOwner
{
ClaimPrice = _newPrice;
}
| 16,475,146 |
pragma solidity ^0.5.0;
contract CoinFlip {
// ERC-20 standard
string public name = "CoinFlip";
string public symbol = "CF";
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer (
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval (
address indexed _owner,
address indexed _spender,
uint256 _value
);
// State variables for coin flip functions
address payable public player1;
address payable public player2;
address payable public winner;
bytes32 public player1Commitment;
bool public player2Choice;
uint256 public expiration;
uint public pot;
uint minBet;
constructor() public {
minBet = 10 wei;
// Creator of contract will hold 1000000 tokens
balanceOf[msg.sender] = 1000000;
totalSupply = 1000000;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[msg.sender] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
function getPot() public view returns(uint) {
return pot;
}
function getWinner() public view returns(address payable) {
return winner;
}
function getPlayer1() public view returns(address payable) {
return player1;
}
function getPlayer2() public view returns(address payable) {
return player2;
}
function reset() public {
player1 = address(0);
player2 = address(0);
expiration = 0;
pot = 0;
}
function flipCoin(bool _bet, uint256 _nonce) public payable {
// Player 1 must bet at least the minimum bet
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
player1 = msg.sender;
player1Commitment = keccak256(abi.encodePacked(_bet, _nonce));
pot += msg.value;
}
function takeBet(bool _bet) public payable {
// Only two players can play
if(player2 != address(0)) {
revert("There is already a Player 2, wait for next betting round");
}
// player 2 must bet at least the minimum bet
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
// Player 2 is the caller of this function
player2 = msg.sender;
// Set player 2 choice to arg passed
player2Choice = _bet;
// Update the pot
pot += msg.value;
// Set expiration timer for player 1 to reveal commitment
expiration = now + 30 minutes;
}
// Called by player 1 to reveal his earlier bet
function reveal(bool _choice, uint256 _nonce) public payable {
//require(player2 != address(0));
if(now > expiration || player2 == address(0)) {
revert("The expiration has been exceeded or there is no Player 2");
}
// choice must be the same as his initial commitment
if (keccak256(abi.encodePacked(_choice, _nonce)) != player1Commitment) {
// if player 1 deviates from protocol, he loses his bet amount to player 2
address(player2).transfer(address(this).balance);
}
if (player2Choice == _choice) {
winner = player2;
address(player2).transfer(address(this).balance);
}
else {
winner = player1;
address(player1).transfer(address(this).balance);
}
// Reset all state variables before new game
player1 = address(0);
player2 = address(0);
expiration = 0;
pot = 0;
}
// player 1 can cancel the bet before player 2 calls takeBet
function cancel() public {
if(msg.sender != player1 || player2 != address(0)) {
revert("Only Player 1 can call cancel function or Player 2 has already entered bet");
}
// give player 1 his money back
address(msg.sender).transfer(address(this).balance);
}
// player 2 can call timeout on player 1 if player 1 refuses to call reveal()
function claimTimeout() public {
if(now < expiration) {
revert("Cannot claim until after expiration period");
}
address(player2).transfer(address(this).balance);
}
} | Only two players can play player 2 must bet at least the minimum bet | function takeBet(bool _bet) public payable {
if(player2 != address(0)) {
revert("There is already a Player 2, wait for next betting round");
}
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
}
| 2,552,517 |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity 0.8.4;
contract MetroBlockScores {
function getHoodBoost(uint256[] calldata tokenIds) external pure returns (uint256 score) {
// equals to 1, to be divided by 10000 in vault contract
// return 10100 to give boost of 1%
return 10000;
}
function getBlockScore(uint256 tokenId) external pure returns (uint256 score) {
require(tokenId <= 10000 && tokenId > 0, "Invalid tokenId");
bytes1 chunk = data[tokenId-1];
uint8 chunkUint8 = uint8(chunk);
return 200 + uint256(chunkUint8);
}
// in python: "".join([hex(x-200)[2:].zfill(2) for x in scores])
// each encoded score has to be within 0-256
bytes constant data = hex"575c7e778e67825c769f5b9b53871f647d6074754b846428805468563c8362886275345c436e5d44417f704f4886448a5f6e5e6ba6507c61866a606d974b7259626946446d5a8f9e405ea6596173919f7e997b666d5748704384574a633b5845188077795f76596c4a687dac2e633c70376b6f507daf5340589459481878902d7d5975aa618e377268a38d67614b64717c795a446f49767a438a724f504b776f6459676b80626f7a655e82554a59797645728083555a53716f9c87378b458aa16b6d6bab6a5c5b696d4a878969518b4d843667556c507a7b8a50615a48705a73323f6e9a83947863498c4c566f76416f395d5d6f987343a471765845763d6d866f4e698a347b7e814d6faf4e4b4f91427e73828767436a656d626238816331415a8a4f2da4604b3952624f828e8a4d755f8284886b7d746e76ad8e9f4a5b6c3b5d81526e8c3f736d5ca15e8b64746d5e605b8f7c5d73686b8739567d72586d4b5e7a74896b867e4c627a644d65827457605565768c8a91834b5c49b15e67536b4a555740444a9456945b797486427b5170715a7d73807f5e618c534b61526d596a630d75835f9088395b4a685a5e417371998f6d6f4d568d9a707e817e336274674a544b5992544f796593766a4c86403b8f815f793a716b6e5b657d83637f52877e78844877595c6a69638a487a975b37834f83686a888d7b4b563d564e485c6f9a4c7e815d8848727a5f447a9d445c6a46756d415763b4866684451e782667784a65587d628b81598b54666d5d5c2e77786962686c7d895961508f41793ca66c577d5b683d3b5557c34d776f937d405a665a7f7b5a4f7973794a6c765976a25339735e5c4f7a525f584e6473524e53644f845699504e6e424b526665702c59925445677b6957536a9485855252495f463b9f74836e5574ad5b776b386a77568c3f9e82746251455e9e9e65706c72573b4192767854697f7197996f8784255f694b42733871406e898c5563795440797e585c3354265c7085557d25574e45834e375a685e2c6e725c62715b7357657372607d9b4b6d65753d8e758a8c7c81576d7e475e70516c6d9e7469547c64544e7a60865861475577529b4e3d593d316f90894b5b4c6c50726a726870706d434e346e4d6a703f6640526f44b8643a7a5b697b71916479704c7c7147796d349f576b7d4f62665f6d775d826669596e458a524c7e6f64785d66838e678272969f91535a7480776329493696655b7f5b6a632b698c676f4c6b5e695b46795726705171844b335f7b59845c70935456667859626998855e778c789d6157667e595c68665242698e924b48775365516017ad607b5a567a7c3ea3825164616f5f65838e5f8f776b7d754f46575833687f694158677bb97285883b70663683614f6f787066882e585d60778a5fae5c38777c43828e4738884742545d278a2350664d89426f6c5c7049684a6f6db35e52934d5b525e564a874a59a4656b5f906b5d7459919b716c767d765d546a34885d488c426382665e694d4d3c536e93917f9176755c80646380766e2f934b69775a9055655d523d6b787f66338284456c516e667265866244614a36666263935f714c957057367d7697766599619e8c4163714c5a8594146b5b746a6e3c477a755e670f7963505e4f524f5d7c775364465f7b62a88e5c48666c5e6082794338606c7559739f794d4180505d23516b6a67327168718775434f732d597a8f4d626d5842918e5996936c6d8584465549534b7a8e3d596b6f5d4e45995f46504d77244969626d6d41576d90a296836f5e45648e595b63596e647863486b74a56e5f776d50794b6e65873f764f5b8f5c6557357866432b7a5e6e5d988a726b7d2f4972497a475e6e657472474f82767d6c6d59096a7c867169725688619d46335369608470695846548f7872524f408779474d6461745a816e69903151898e7a644f596e6540884a7572604184707f334d893d4c3b7d727e5c3d8652964745494f747e778860b16180795a685d6e6da8414d7479827b3e677d4181738a93986c5534566da174536b54725b76705f5b65586561917b3677886342985c244f7371628e495d66406786624d5161497f5c2f4f798523769d7f7b86ab47577d4b7c8d644c6d906c5340775e58345c5f6d404a4b8d5c494e553d85896c899a469b913f225e90707728795b6f5a92559869764b6a88a5546c61677b52639688598c413f5e917c68436574536f8a56734d3e666834826b45a842675c625049868a446c5e448a3c7c87704e7f7f3e7f7d8876697c6a968d695d646e7c493b6a80af6b666e8f5e797c7b7451677c555d65a17e34615f4e4ebf81717177747f6c7e69747330805f585d8a576b589d8c578b67414a75698d786e8257455d77654559b683755a7f5c9c5f765467656d4e625c688062739b5d5a5a4d9175a35f6e5b4e5747498a6d933b70674c65515850536c5ea65872568b5563408b82767a626b3e2047677e53736a48734b3d705b92644e6a7858635c858b658c9672506a78486f5d817775807a6e753a6493821c80a45c6f4d5064485a762971713586766f987b6c6c5599736649815ec47b81312757c8707e77897f5b6f7b7e76634d867572485942646b6c336b9e7d7b58848d92688c5646600e527e6a996449478e59616a75848b65918c8975349a78535f745b9a82708e70784074917d5547695a6a754c837250874159836543539749536b836d9582666b60527252685b58757d578091583449854973407b5d5f4e6077358b739275916c8b8c3a672a3b5178666c64794072735b7b445852809e816d4184709964423d5064533f85697b4b7476545d8b92525d584a4e48684a54566871366d44557a52505b68648886593d567b6e3f698c47969067394a885858815c734470419a7d8d7975676f8371798a427bb771693969a269546f746e79715a9f5f282e307d8f795c4c5062284c727a967e5c544f823d71677851645f5291677d6c617c9a6c5f9241508e877857832d4d8a565a717559535d4e2b545981814083589d947161577ca76560347e547a59825f6a9a86737f7f647654576859433751885b746f61a66a6a57754f51748e6276594d65964f816c624b675d825f774c5666607743508a2d7a4e9750816b555e593d695940973b3d79736261775b886a70a2286643ae999477618f577aa53e5e737071535c736d6b838c556472711e377e204d718684674f7f8d7b4a5f90658f6d6b514b6f59916b7c7895576c54436664a1587b4c6c53647b52518c4c5150683d646a83b75f8b76615158975a42564d62896268775e6875826c89767e84516f248852726272746b80316f507c6f74684d8b4c5e628d593e605f506a6d8162479b4d72995c653c324e84436881a551725e6f638f86765a875d88586b765b77676a1aa1556e826268725ca1526f6f6f4489629c6c3e8f32858b47445069693c547166558c4e755e697d7e45627760646a5f645b784049593ca4657a6f699268591a4c4451425574716e566a5780697e577b944f5a5f746949856f593c8e204747568472677c0b3d6f99568f816d73595049227a8d6b7d7e408e8650686c6346576567494e597c633b5d586c5c6268526c81797044485c5660836d5f666d4f44897546884781436f5477989f337355616e5e6766956c365c885b6f5e6572709b395e754e4c7659596f764d83707f8a6a3e2b7e5aa155527977507e4d565508515c76681d8e5390615566578257736176817d8f5783756a91895b2e7d84376c7e5b627d6d414d7931514c406e3e5f3d519175542e5e4d515d34835e6e70818542877a50794a5d856c6f6b7d4674633e5958754680825156674962628a74a2639269722a456d386c6975646a9985737468622c6e57725a4577788374724476679775683a4a80706a64378a754a5f6e52303c627d35744a5a6d7676ad8682966c884c90185b756b4f4aa27c6079758a6b7b70755e585335596d6dab084239a0735ea164665e78746e40695b436d595a4489726354698c5e2a4994aa70648958883e30668b595d8b7a4c6296795a4e42418c6a797d51656c7b60555b78524e727b6a6357765368537f51516a3e8f81847a685d7e4a6371a2664d724d6a26763b579b4177396d617e7d7849628740704f6d64a0615c506b7956625c76a07c85805d6d527170795a4f6f666f606970618168878e80657d7dad30563f3b6a52713d589d4ca27863663e5f7789736a7f515aa66c883988579b7d8d5a57815b9d874a77754894913a4a687f514861a579545c68a26a684e4a604a74a08f746056776b68657b8e648c798f8e6f7e778f7344706d504c5d6caf885d429257587b845b5c62938a52777a6b3157573f44923668616e58585c3356583f9055837e9f649375772d9d6b786c896b7652665b70744971546e1c6c8c8272787b6c62684f8363467756884b34386a8c4d6f4e6531667c577b555d7157868b6a374e46566b857487748186823f76525b6e48473118835a785b4e77437b6b5f4e6e3a8766638976765f9c6f24975d60776c9755605c68836b64774d617052668b628aa978705028406448785a7e8a89844973797c618d4f5f4b81754c464d5f9b704a7163608b73393f53633473835b7a85254b1b6e6d4c655e6ba66f4b79434d435a4b3b727b76566c66556a69428f8a6071649a6a609451573b807f777b866b7097917c406e5c6344813083589e6e686a5f666c5a6f40774c55856e415a6385675076345c4957a485828b5056415d3854609d83706c634e96875e474a72609e85555f6a538853676f85764466966c883c63676a5437695559766a61839b706d8f7169178371398ca36b5c587749405477462b6a498e5a794c48a0667c59477472525578575c50385a6389693b588f717c86797e4a5662495b3b5e18667372a181667f965b605f90637e6d9140816a586a76484d5a695a52498d8e3f475483877886628e3b32636b5459764c47862d5e5568515c885358425652656e3b2d9b5b29754b6557774674365b53504d7a908a5276885f33444f6b95555f615b756174695561a6626f777c6f68a85b9c827a5f7e57694a734f5b616b435d836d8da64a5454606ca38259197a4d6a9460647e5f4f6d503b493c5a845ba7916376645d644c8165765f4687845f4d68767a645e7092735e812d874e804f96876078564b69826b816670574869488988695d4e4495565072776c718d485f3843606970903f6135597800877f6d7b6c488749725c7b82557a7f804269788074947292654a607466957b6279497fa28734583d8c6f738270886a706065698148b34f897b6d554f46537b6f815464754b78553e5459527f5a8562607d954f68917d53317642629f547b8753437a273b63a8627e737f7c9e527474754e7d868b53647a723c93634f679d6d757e6052615c675d9c658176431c4b1a6c77659e425591556c7557407959716c565a768b5c6a6d6d5f927b67595a5f6b6757807b312e754582627c92b35289474a9972658367594f62708e76a54790595c887b6c6274b17a6d6363aa624767799270956a834f8081a8925c604e658b7d525e1c485367755b655b6044764d3b7b473f286450664b7a65495e6766418875ac69617f544c6b425670716d8b797b6d468d706b51676e3f5eaf523e64706962687941577f6e49747e643d5d553b3a9b5348356d6a58438c319d68376975799e6b5a45725f8f5d654f74376a7d9d5a2f578a4a78679a5e67674d60536e5d187c8077876e7c6877b53a3f554280286d887c6a597389377c567d38665f814e6f848951935c5f675741806643866b76825b827294408b8c59445b5767714e93338584404c64665887788957706c6e628d8b51415a815c9565306e52465f6f784142437f714c6252424f7841898249a48c6465648a777b926d51467582a077973d5e52594f3a8466644755636f3c4b5e5167989965684458a4629235668a6d34785b86715c59614d6d46995d50638841557d2c186c71707f4b56728d7b51705b547e6e5d7863858d506d677f544b77636868784a7378ac676b39926f5b62726f725473497ec360907e3f653c4b5882535c745c6e48833b44745c61669658428c6b3f426a0b6b237865816f5250798c874a885d7f7f2732963e6594813672543b745d5b903f3449576866577ca3718c778b9c39336779785a54335b424966866566507a2fa057715d65746c5d66504a5faca3918c724f626b60595d877f646d89703775348e5a7e6e926930515f476d4e397236898983695a7d506967327e8f5f5c7f56677d5274695c7b6a4c7f506757756c56944a4e617a82425e68bd67885083684277795a94586c857566406d648355765e33a77175555a7f754e46596a554e33a84f9e404b71796e8a3a915a944f7c7256598a50745e998085577f60606d625d7b436a6a61547273688d5f33612158771d7f8c5733583845759d634f64694f7025874d754f55816a7c7d6d69744f7c56596d95514c828e5a6a6d5d5b883b556692887967676166528364746b95526f887e517672544534837a516a24694f4869876d65675a7e736f833a62619f5a84796f703e5d6ba551498e749353483e68304a6482866c8a64238c854172558c668347617a4a836c7d7b5f4e596860814a6e714d7d675a529c346b7753486e4b8b6682305365507a524e9858726d686d4568722d5556658b23495d705f5c5b57626b45554219656b9a506991285d836c7a37693d51276436775a674a658a505775734f3f5f6674838b786d606e59757b745d32435478483478324d705e97575b5756675c384852666a565f575172496e2e6741706e57686c5f4e257056543e845d3a698a89657a50908a5f785d506b69766295675c6967649b4a477b5b715d74a54d584b8d85736f756932537077523e55679b69a8669f58638c41756e5d4e67486719883f5b8c6c815a776e6c8146806454697f627e618e58444451847440995363825d685c8c7365828f7b55887f79494769913a718a47637042696b7f73517a6c58584c5b837038957155753a6d38372e645c6e3d6376778b7c56a34d8b96545f788d515b7f639c3765464370634e4b784f4153784e7845ab8c6466677359623785506163774a887561799072365c61354d408373478f953696956e617464613a6d5d6e6f6576654369635e4b94238095887a71825f686a848d8c50584750684f857b6f57527873796ca85d6b4d737a7352495f5c8e7b726d757b851a543b717930906e756e5d8eaa88667e54624d93534d92449a8f3f5182827c5e5b7972656a57637c685e56726c71635c7a62687b57498d927d456c5a7b9d77547a4874a046707e5286624b608f945b746b82815d73512b5e874d89516955695483817e76b12984c6577060556e6896586e7b6a7a645772693c757460858f2d606c576e4a6689876267a697885f52845873864f664460583b4994925961679e57655b5183673e6673504f63746673476b85626636b5639b6b914a987e75345f586869817c952aaa43557a3b7e78626d785c8f81728983665482507b3999808d666a3c806073708a817c855479926b7e407c4b6d72932b67445b6a6466687c695c6a7b2982409f903e4d5a717a7064404c3f599b55725f5f5d918156698e8887615a893b3541493c244c3f5c5a5c4d4d996735585c5f895d70b89188556f806748614e3b5b545b78b9657264824169749d587d4634457444857663676967865e415162763d466e6d4d6e5444705b9257687d684b7aba7160565d4b3d5673755d538678915f455d7d6b7e4a54536a606b616180b0528967743867694a804e6352627245c0655b91725e7d616e72735952ba735666704f5e82658e6c47897758466c8d8f654f2d855e5264669740706b71686d97588456513c863b77807b395d5f606d68324e51798d534f745f0a5e7d765a6b716874774e407d5d4a7e385052662958696683548c6e647547426a394f794f545070745b7e796e6f5d856445593e1f4b65567c774a5d773b6345716d709f6c5d4a6c7e69655c6e9a4e559e7eaa686474aa5f606d4d5a8a4b79616755653b45335553837a6f6c9071296e486d52693074827d9d4b7b4f6c754d8248686d6e4e767e3f6063804d5b6f737a6361514f734f5c6f3d8a634d6e886c688532606b1a315a886d996c7f466c72907657654c853b98363f4d966e2b57857b516776757d4e435b567e6e495e445c573955547b3b79696e76595b6e3b61824b737d8b7e7c82475d81492e7a7b5f5a667778845ea55a673e527c3f4d553c708e887a60766a4e5d5e497a42715b68427e7b4545a4646c69565a559451558568696251907c7265648262446946af4e864d7c62816c6b96894884558748845c50876361686a82a14b4e6b6e64746f61767749739d5d9e4b6a5293956f8e509643837c455367507019547d56617f1f927f8a6c4d575a69446e6a686d9a1fb270a36a8137717fba776281583d58424f5c666b705f4248518e4040b46d4c5c8b70665796984361206a867c6082805854995b384a51865452675f37659c4087886a9563425b598a53726f818073618b4e5d34a55b714f767d6f798c69746e445585684a72774c36616c6e465e6b405e6a4e634a6b5d7d625b566da487665b858a6f95775049709a634b655f4e5f555c726f4d4597577f6c735d6656af89717c3b7c5e685a765758583f91517074604661418d37814860896543897e598e615a4b788a4b435a9259956f4a3a63566940406e98827e653f718958355c854e65745f726c3968695f6b627b466c417078997b7480636d77695a2d58848074ae816a6a57684d735e6c5c866e7b8a704761857d3f6f565e68676d6555476e71534b3f5451808e727f80938a61844a7e4c7c5b82527b1c53806b68644e6a575164518e4e504f4e7f398d4f47727385825a4c854a2c4540703e747f5489675811528b866b30746eab4d6974774e6a6b6c6c375974805c65779c89656d998f5c5e4f7a4a39755535797041847d694e4a636d40905d6f453545537787483473624ca8bb71aa5b4a446e5c523dab7267665c66935e5d747476507c596c6d6282975e4e60b1855861536e506d44527a4b6b3d47657164418cac577a50988f6630656a739d90387867484d2662769b836280699b676999897c896f625e75536f586372753966567787696e7249704e847a615aad6c786b465c7c628a6e5d6a8143547e9f72ab7735806383417e2f7684435982917e684e5f96976b486da1769b776b55767d7b5c71573e8546347c675e5d8f4e746768978392836b318a7b6b4b865485682c5f5c8d52a761796256743e704c498c3f48646fa1687f65626c648a954d646d626e658e697c836c9d7397b2716d5463845c206a4449814c7e846e7182796b7c887232ab4d6c8757555e5c646056568758af4f8166715699828e5161ac654e7d673f397f7b5a5368ab8f6d701d8c84557c745f7b4f536a3c6b764074784f5d646d5e795c72483d8f9357738b7f8c74824b704e4e77538d58616283984a7b63325791717764976a6e5f7a824d6b529865547497855e546c3d6382736b7c5062ac50706a4b608770688d7d765f906d62476b5a676f896b5e683b4d79775f1589696a523f56765e71655a636f72a177625830835b5b558766607eaf438d7a457d517d6e557647603868948d728377615255845a7145787a284e6c4c694178589560896e744ca13e40706673637c5981625e537f468764533f7f674f9c55666e7587735e778c6b4c28a259855e5fa0596658746b4c5484645190595a3a7472575290715aa1445a6365386159678e5891556e368567a05453384071385b0f41a96a7a58584a546e5c766d817a61758d787762918b6e6588465d8a691d8e538b84435248a467657f626daa8373937660a992a4599c73435470802f5634567a35667a835c744e5e8d814468694c4a4a5461918a5e59565155778d4c396231867d567960745b50874f51978e565d4a82485a636f99677352676b33774b2e93559b48537e30917878706e446f6966309156623d2e3d3c625c2b77324a5e4c52837e679058667d4a89950c5c695c877a47a583453f64587f776a866b6c46576290546e655d704a2f434d6f234656424e555c6f8953905e1b687a6967825d997386614e657366985b7050375f535f4c6d858d6156674474759b82644e635b604a5b53639439704f6f736e5c3c8367524c70606e859152ad716172906e655a76718a9b8e88865e8b536c636b9a56836084752095675183636c5970538c647e47627d79666a5d726d5950744d5753728669656e718b663b67c3757e546f634a5f596b99577f70766d78544b91857a4e5767757876386e363e6f664d927558466961719b4b57563e4b5e4e4c7d4979812b889287a06f588d8b9c633d43459f83724f6e582a5490459066979467476e36777b547c8d3a766e647b66895f8c5f6d5566a872388058245d62447359926c3c65a65c53806eb9737a7c577b6e704a7b7a606e7951598759624b793f7d605a664f9c825f606d4d564d7a777876944c6c6f7c7f938ea37a3f6986637c7072575e77912844998b4e858b436d68595961648f6c406d663924526464907a585c574b717252a74463553b646f674e6765578187516161584e746d7c556d47654697a4885885566656714d7f95ab447a497a4b37885d7f71598268746f8c5e704871739167ac6f6d78667987421a5c6c79794a759d706bab4c4c59757c51666f9190526fa46b656654536f6a6e9779795f6b6b6d996f4f648e6084736f4d62af776b8e55647276405e609862907a61696e6550533e488d4e5375616a8a575f634b354f556e7373719e914d957e6d6462345e1a4470603a455d5f64bf6a2d5d4095478d2f7d704c7c995b66656480607147947e8c7c444a707d4b556d465f567a606b69238b568867607255537b7e4a3e74125e59505b9b4d5c78865a6e77765f9f874f7148806c56786e9b5f845c3cb167628e5d686d64688c85659d3262693f9b4862365e495c69ad65635a7316537f7756887358897c4d694c736e72586f38765a8f345e74555f4d7d75ac37427163a67b75a24b5541764b45794779775d52678471675e7e5b5a5d795b63727e85596286805f797a52565d466d77777b4d59132e6061595f647160a5575f8168847b4e557d9f64649477576b762868448e758b707c735e4c865cae62897171312c7a779a61889a7a581e823787963e79af6b5055486253534b505c5194748b55585f8aa335967e86546544756e88426189815b4e6b6c33426b6451676f5e556c527930487d50846562796a756b83532d3748325b8b4693844c544d71557356775f5b7354625d336b4a6a6c364c47682f50575aa35c4d63602b4b51467b90a25c7c5c8e7a771b5b9c73927f69856c7f3b916278607751776281555d5e67605f786951536c4994614192766155bf545a5ea86b7642a55e72544e43494c747f6d705b513f45766a4d404e69717e78793937856b566479677177697538668b7546444866505c5974717d487a6251599e4b636280697c6d8c5976507f4b78af6d6066966d2b3008689372877d4e813973495a4d6348616288594f675a505d4c558a82716885205966766d4a73806879446c7e708b5153378e8563547d668741465750605f677e85c3668671707273624f7c5aa179907f7d7d51597030518e75716a67507b5c4e583c707b8353707b7b5a5a6a306a76687f9b8f737c45ab4689718d3e4c469d626b616b6254a64f905978766a7b6c777f68632a726c759d3e657d386947684c7e1f627d8b7c6576604d59466a844a7b96593654646faa644eb55f82514d5e1f375079945d3a517e9651714c437a7b413881767262545f7c546e5e54627a618451606f58494530796155984c208d73477caa78a2927b639590917c7563506f72717265733289935756787b70504b607f99547070645493913f55607e8375797890754c6b627f5b544d534e89817a4e626c5f576d695b23725c99846638665e86712e9662835a50a2574d7f3753125b574552636f91665833765d67857e5c6c595443636697355298854150534f5f7e7f59ad30b34e4879516a444c8d4749ab655077506d4c819b633669589f45925273697676477171366d69526584725f6b906a755c8f7256695c34955e73696273a880687379496e3b68b56e6462569e3f764f6ba85585665838986e7c535b527e623176436f56724d7c5a4f8e897b4f787d4e976a234c545b8c34594f4f5280474b9b66644f8b947782aa8154b16880446c9f4245526399366c386b5958786467747e84ae44745c70678b7b5a3a5d546a743b707c5b656457378a6c5b4880726a65795c463b5d4d794333ac55666d61623a8ea057317e99646b73774e8d867276666172974d5d6d537e6a931a8b8984685d643069573f5f633772587761846f4b5f8a7e8242585ea4606b83903b8228923e6590556d4c7334634b645d783d725b638b48637abd4a44a775735b584e8871a9435b756d52435a5e6e454d79794d846f9160696959501e7d6d618075935e6b5b7c9e4cae87955ab2536a7f965755643f75655c8044505a5a5179873f256b7867699a6b8a9094476f5e6b4846595770495a4c69498a9e5391466496462d4a6f446c8047418566653c2388688c7d5620707d6c564853598451828c3e396b6e8a797a8644777c646c6884567030659b714d6f76036e4c5f9fa0758d7c537f8a5474753f8891c3925e4d286a74684647535e6067648d6d60505f59444e6aa16d80547b1b766a57617c5a53325f449d63687795784345857a694daa916e664b3ca23d597452845a873d883c305b916f835d6d88499c668a95705a934d48525578ad3d5954726579604e705e6c7a4694909d47713646316f3a6a6f72885f45615969834e78597655416d686d645d34b27a724e57674f7f65527476427366665f3366a537545c48701d8f83675b426b64643796783b3c79ac554c685443878a485f956776715d86446d54548e7a8821984f6096678e8444814f3c717f53b65ba1903d7767719d825c6b387a506528a05c9a6d556b5d88616f48577c7b6e416f484f9b3b5b5d735f4c81935a80617d78708b8951ac5a643f519220333e7c60995755825b88544986405f71736284785571717d4c53032f726651684e4e6c507135705d6e5e67256f6767405f4068655e6e5d607c65715353766c342262947739404955779c35865539604d878e5b909b4d5c397077682b437b70796a51b46e71a14a85797e745584685b73677a8e61b8634b3d845f63936c456f6c50905f5d71376b793b62644c735d4376587d55327869938b667079437f877a617d776048af675863848c364b824b5572365968676f7d5f55503e777962614aa26b4d5a9a7e95896f5336734a70596b6a4d5164677e5d87777866671c594f9264606a55746a6e5b4a626c6d493a5a417a513849584979824457646a40664a665064717c47814f9597545b4785634e71342e61923a76908c74736c4b564650516d56c4807a893e537d514e544aad7970b242554d7e744ba573705d8a405e807b5b7a76657d81a86c656e5a547e5f5060868672565b339e6d753d566c785a787d8a8b6972423e578074738868659c44599f6a7b79573d649857946b817e6b67a6451a297054956a4a5c655b6a814369495262854a4f9d617f727e575788426a896c68644f7c99566f125e708232304c6f6e2a78514c3d2b529d787a556d591a496c6f9ca5924e7314418c785677475033304e8d7f7052956f357a3e56557c9b597c56495c88654d5c7f6b50435a65516f3946687d6f69575552545a5b7b65699948977a626f67683ca8855f60616d6a642c5a876d775c6675806e6f8b55522277638586615aa4596c76257130638c647092685e596e90909b9e62643f596b58947274a55e982e4f754f7c515e613d833d755b60285595835f84598678";
} | equals to 1, to be divided by 10000 in vault contract return 10100 to give boost of 1% | function getHoodBoost(uint256[] calldata tokenIds) external pure returns (uint256 score) {
return 10000;
}
| 15,311,889 |
./partial_match/11155111/0x37523dFFe2a485Afa8Ef662827acF9E835C040Bd/sources/Users/chichke/Documents/Work/Freelance/RealT/bridge-v2/contracts/operating/ComplianceRegistry.sol | Updates attributes for a user Intended to be called from a trusted intermediary key Throws UR05 if _attributeKeys length is not the same as _attributeValues length Throws UR01 user is not found _userId the user id for which the attributes are updated _attributeKeys array of keys of attributes to set _attributeValues array of values of attributes to set/ | function updateUserAttributes(
uint256 _userId,
uint256[] calldata _attributeKeys,
uint256[] calldata _attributeValues
)
external override
{
require(_attributeKeys.length == _attributeValues.length, "UR05");
require(_userId > 0 && _userId <= userCount[_msgSender()], "UR01");
_updateUserAttributes(_userId, _attributeKeys, _attributeValues);
}
| 3,536,128 |
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MIT
/**
* @title Genesis Voxmon Contract
*/
/*
██╗ ██╗ ██████╗ ██╗ ██╗███╗ ███╗ ██████╗ ███╗ ██╗
██║ ██║██╔═══██╗╚██╗██╔╝████╗ ████║██╔═══██╗████╗ ██║
██║ ██║██║ ██║ ╚███╔╝ ██╔████╔██║██║ ██║██╔██╗ ██║
╚██╗ ██╔╝██║ ██║ ██╔██╗ ██║╚██╔╝██║██║ ██║██║╚██╗██║
╚████╔╝ ╚██████╔╝██╔╝ ██╗██║ ╚═╝ ██║╚██████╔╝██║ ╚████║
╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
//
contract Genesis_Voxmon is ERC721, Ownable {
using Counters for Counters.Counter;
/*
* Global Data space
*/
// This is live supply for clarity because our re-roll mechanism causes one token to be burned
// and a new one to be generated. So some tokens may have a higher tokenId than 10,000
uint16 public constant MAX_SUPPLY = 10000;
Counters.Counter private _tokensMinted;
// count the number of rerolls so we can add to tokensMinted and get new global metadata ID during reroll
Counters.Counter private _tokensRerolled;
uint public constant MINT_COST = 70000000 gwei; // 0.07 ether
uint public constant REROLL_COST = 30000000 gwei; // 0.03 ether
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo public defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
// to avoid rarity sniping this will initially be a centralized domain
// and later updated to IPFS
string public __baseURI = "https://voxmon.io/token/";
// this will let us differentiate that a token has been locked for 3D art visually
string public __lockedBaseURI = "https://voxmon.io/locked/";
// time delay for public minting
// unix epoch time
uint256 public startingTime;
uint256 public artStartTime;
mapping (uint256 => address) internal tokenIdToOwner;
// As a reward to the early community, some members will get a number of free re-rolls
mapping (address => uint16) internal remainingRerolls;
// As a reward to the early community, some members will get free Voxmon
mapping (address => uint16) internal remainingPreReleaseMints;
// keep track of Voxmon which are currently undergoing transformation (staked)
mapping (uint256 => bool) internal tokenIdToFrozenForArt;
// since people can reroll their and we don't want to change the tokenId each time
// we need a mapping to know what metadata to pull from the global set
mapping (uint256 => uint256) internal tokenIdToMetadataId;
event artRequestedEvent(address indexed requestor, uint256 tokenId);
event rerollEvent(address indexed requestor, uint256 tokenId, uint256 newMetadataId);
event mintEvent(address indexed recipient, uint256 tokenId, uint256 metadataId);
// replace these test addresses with real addresses before mint
address[] votedWL = [
0x12C209cFb63bcaEe0E31b76a345FB01E25026c2b,
0x23b65a3239a08365C91f13D1ef7D339Ecd256b2F,
0x306bA4E024B9C36b225e7eb12a26dd80A4b49e77,
0x3Ec23503D26878F364aDD35651f81fe10450e33f,
0x3d8c9E263C24De09C7868E1ABA151cAEe3E77219,
0x4Ba73641d4FC515370A099D6346C295033553485,
0x4DCA116cF962e497BecAe7d441687320b6c66118,
0x50B0595CbA0A8a637E9C6c039b8327211721e686,
0x5161581E963A9463AFd483AcCC710541d5bEe6D0,
0x5A44e7863945A72c32C3C2288a955f4B5BE42F22,
0x5CeDFAE9629fdD41AE7dD25ff64656165526262A,
0x633e6a774F72AfBa0C06b4165EE8cbf18EA0FAe8,
0x6bcD919c30e9FDf3e2b6bB62630e2075185C77C1,
0x6ce3F8a0677D5F758977518f7873D60218C9d7Ef,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0x82b332fdd56d480a33B4Da58D83d5E0E432f1032,
0x83728593e7C362A995b4c51147afeCa5819bbdA1,
0x85eCCd73B4603a960ee84c1ce5bba45e189d2612,
0x87deEE357F9A188aEEbbd666AE11c15031A81cEc,
0x8C8f71d182d2F92794Ea2fCbF357814d09D222C3,
0x8e1ba6ABf60FB207A046B883B36797a9E8882F81,
0x8fC4EC6Aff0D79aCffdC6430987fc299D34959a3,
0x929D99600BB36DDE6385884b857C4B0F05AedE35,
0x94f36E68b33F5542deA92a7cF66478255a769652,
0x9680a866399A49e7E96ACdC3a4dfB8EF492eFE41,
0xA71C24E271394989D61Ac13749683d926A6AB81d,
0xB03BF3Ad1c850F815925767dF20c7e359cd3D033,
0xBDF5678D32631BDC09E412F1c317786e7C6BE5f1,
0xC23735de9dAC1116fb52745B48b8515Aa6955179,
0xF6bD73C1bF387568e2097A813Aa1e833Ca8e7e8C,
0xFC6dcAcA25362a7dD039932e151D21836b8CAB51,
0xa83b5371a3562DD31Fa28f90daE7acF4453Ae126,
0xaE416E324029AcB10367349234c13EDf44b0ddFD,
0xc2A77cdEd0bE8366c0972552B2B9ED9036cb666E,
0xcA7982f1A4d4439211221c3c4e2548298B3D7098,
0xdACc8Ab430B1249F1caa672b412Ac60AfcbFDf66,
0xe64B416c651A02f68566c7C2E38c19FaE820E105,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0xBe18dECE562dC6Ec1ff5d7eda7FdA4f755964481
];
address[] earlyDiscordWL = [
0xfB28A0B0BA53Ccc3F9945af7d7645F6503199e73,
0xFedeA86Ebec8DDE40a2ddD1d156350C62C6697E4,
0x5d6fd8a0D36Bb7E746b19cffBC856724952D1E6e,
0x15E7078D661CbdaC184B696AAC7F666D63490aF6,
0xE4330Acd7bB7777440a9250C7Cf65045052a6640,
0x6278E4FE0e4670eac88014D6326f079B4D02d73c,
0xFAd6EACaf5e3b8eC9E21397AA3b13aDaa138Cc80,
0x5586d438BE5920143c0f9B179835778fa81a544a,
0xcA7982f1A4d4439211221c3c4e2548298B3D7098,
0xdACc8Ab430B1249F1caa672b412Ac60AfcbFDf66,
0x82b332fdd56d480a33B4Da58D83d5E0E432f1032,
0x6bcD919c30e9FDf3e2b6bB62630e2075185C77C1,
0x4DCA116cF962e497BecAe7d441687320b6c66118,
0xaE416E324029AcB10367349234c13EDf44b0ddFD,
0xc2A77cdEd0bE8366c0972552B2B9ED9036cb666E,
0x23b65a3239a08365C91f13D1ef7D339Ecd256b2F,
0xE6E63B3225a3D4B2B6c13F0591DE9452C23242B8,
0xE90D7E0843410A0c4Ff24112D20e7883BF02839b,
0x9680a866399A49e7E96ACdC3a4dfB8EF492eFE41,
0xe64B416c651A02f68566c7C2E38c19FaE820E105,
0x83728593e7C362A995b4c51147afeCa5819bbdA1,
0x7b80B01E4a2b939E1E6AE0D51212b13062352Faa,
0x50B0595CbA0A8a637E9C6c039b8327211721e686,
0x31c979544BAfC22AFCe127FD708CD52838CFEB58,
0xE6ff1989f68b6Fd95b3B9f966d32c9E7d96e6255,
0x72C575aFa7878Bc25A3548E5dC9D1758DB74FD54,
0x5C95a4c6f66964DF324Cc95418f8cC9eD6D25D7c,
0xc96039D0f01724e9C98245ca4B65B235788Ca916,
0x44a3CCddccae339D05200a8f4347F83A58847E52,
0x6e65772Af2F0815b4676483f862e7C116feA195E,
0x4eee5183e2E4b670A7b5851F04255BfD8a4dB230,
0xa950319939098C67176FFEbE9F989aEF11a82DF4,
0x71A0496F59C0e2Bb91E48BEDD97dC233Fe76319F,
0x1B0767772dc52C0d4E031fF0e177cE9d32D25aDB,
0xa9f15D180FA3A8bFD15fbe4D5C956e005AF13D90
];
address[] foundingMemberWL = [
0x4f4EE78b653f0cd2df05a1Fb9c6c2cB2B632d7AA,
0x5CeDFAE9629fdD41AE7dD25ff64656165526262A,
0x0b83B35F90F46d3435D492D7189e179839743770,
0xF6bD73C1bF387568e2097A813Aa1e833Ca8e7e8C,
0x5A44e7863945A72c32C3C2288a955f4B5BE42F22,
0x3d8c9E263C24De09C7868E1ABA151cAEe3E77219,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0xBe18dECE562dC6Ec1ff5d7eda7FdA4f755964481,
0x2f8c1346082Edcaf1f3B9310560B3D38CA225be8
];
constructor(address payable addr) ERC721("Genesis Voxmon", "VOXMN") {
// setup freebies for people who voted on site
for(uint i = 0; i < votedWL.length; i++) {
remainingRerolls[votedWL[i]] = 10;
}
// setup freebies for people who were active in discord
for(uint i = 0; i < earlyDiscordWL.length; i++) {
remainingRerolls[earlyDiscordWL[i]] = 10;
remainingPreReleaseMints[earlyDiscordWL[i]] = 1;
}
// setup freebies for people who were founding members
for(uint i = 0; i < foundingMemberWL.length; i++) {
remainingRerolls[foundingMemberWL[i]] = 25;
remainingPreReleaseMints[foundingMemberWL[i]] = 5;
}
// setup starting blocknumber (mint date)
// Friday Feb 4th 6pm pst
startingTime = 1644177600;
artStartTime = 1649228400;
// setup royalty address
defaultRoyaltyInfo = RoyaltyInfo(addr, 1000);
}
/*
* Priviledged functions
*/
// update the baseURI of all tokens
// initially to prevent rarity sniping all tokens metadata will come from a cnetralized domain
// and we'll upddate this to IPFS once the mint finishes
function setBaseURI(string calldata uri) external onlyOwner {
__baseURI = uri;
}
// upcate the locked baseURI just like the other one
function setLockedBaseURI(string calldata uri) external onlyOwner {
__lockedBaseURI = uri;
}
// allow us to change the mint date for testing and incase of error
function setStartingTime(uint256 newStartTime) external onlyOwner {
startingTime = newStartTime;
}
// allow us to change the mint date for testing and incase of error
function setArtStartingTime(uint256 newArtStartTime) external onlyOwner {
artStartTime = newArtStartTime;
}
// Withdraw funds in contract
function withdraw(uint _amount) external onlyOwner {
// for security, can only be sent to owner (or should we allow anyone to withdraw?)
address payable receiver = payable(owner());
receiver.transfer(_amount);
}
// value / 10000 (basis points)
function updateDefaultRoyalty(address newAddr, uint96 newPerc) external onlyOwner {
defaultRoyaltyInfo.receiver = newAddr;
defaultRoyaltyInfo.royaltyFraction = newPerc;
}
function updateRoyaltyInfoForToken(uint256 _tokenId, address _receiver, uint96 _amountBasis) external onlyOwner {
require(_amountBasis <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(_receiver != address(0), "ERC2981: invalid parameters");
_tokenRoyaltyInfo[_tokenId] = RoyaltyInfo(_receiver, _amountBasis);
}
/*
* Helper Functions
*/
function _baseURI() internal view virtual override returns (string memory) {
return __baseURI;
}
function _lockedBaseURI() internal view returns (string memory) {
return __lockedBaseURI;
}
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721) returns (bool) {
return ERC721.supportsInterface(interfaceId);
}
// see if minting is still possible
function _isTokenAvailable() internal view returns (bool) {
return _tokensMinted.current() < MAX_SUPPLY;
}
// used for royalty fraction
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/*
* Public View Function
*/
// concatenate the baseURI with the tokenId
function tokenURI(uint256 tokenId) public view virtual override returns(string memory) {
require(_exists(tokenId), "token does not exist");
if (tokenIdToFrozenForArt[tokenId]) {
string memory lockedBaseURI = _lockedBaseURI();
return bytes(lockedBaseURI).length > 0 ? string(abi.encodePacked(lockedBaseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : "";
}
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : "";
}
function getTotalMinted() external view returns (uint256) {
return _tokensMinted.current();
}
function getTotalRerolls() external view returns (uint256) {
return _tokensRerolled.current();
}
// tokenURIs increment with both mints and rerolls
// we use this function in our backend api to avoid trait sniping
function getTotalTokenURIs() external view returns (uint256) {
return _tokensRerolled.current() + _tokensMinted.current();
}
function tokenHasRequested3DArt(uint256 tokenId) external view returns (bool) {
return tokenIdToFrozenForArt[tokenId];
}
function getRemainingRerollsForAddress(address addr) external view returns (uint16) {
return remainingRerolls[addr];
}
function getRemainingPreReleaseMintsForAddress(address addr) external view returns (uint16) {
return remainingPreReleaseMints[addr];
}
function getMetadataIdForTokenId(uint256 tokenId) external view returns (uint256) {
return tokenIdToMetadataId[tokenId];
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = defaultRoyaltyInfo;
}
uint256 _royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, _royaltyAmount);
}
/*
* Public Functions
*/
// Used to request a 3D body for your voxmon
// Freezes transfers re-rolling a voxmon
function request3DArt(uint256 tokenId) external {
require(block.timestamp >= artStartTime, "you cannot freeze your Voxmon yet");
require(ownerOf(tokenId) == msg.sender, "you must own this token to request Art");
require(tokenIdToFrozenForArt[tokenId] == false, "art has already been requested for that Voxmon");
tokenIdToFrozenForArt[tokenId] = true;
emit artRequestedEvent(msg.sender, tokenId);
}
/*
* Payable Functions
*/
// Mint a Voxmon
// Cost is 0.07 ether
function mint(address recipient) payable public returns (uint256) {
require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one");
require(msg.value >= MINT_COST, "not enough ether, minting costs 0.07 ether");
require(block.timestamp >= startingTime, "public mint hasn\'t started yet");
_tokensMinted.increment();
uint256 newTokenId = _tokensMinted.current();
uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();
_mint(recipient, newTokenId);
tokenIdToMetadataId[newTokenId] = metadataId;
emit mintEvent(recipient, newTokenId, metadataId);
return newTokenId;
}
// Mint multiple Voxmon
// Cost is 0.07 ether per Voxmon
function mint(address recipient, uint256 numberToMint) payable public returns (uint256[] memory) {
require(numberToMint > 0);
require(numberToMint <= 10, "max 10 voxmons per transaction");
require(msg.value >= MINT_COST * numberToMint);
uint256[] memory tokenIdsMinted = new uint256[](numberToMint);
for(uint i = 0; i < numberToMint; i++) {
tokenIdsMinted[i] = mint(recipient);
}
return tokenIdsMinted;
}
// Mint a free Voxmon
function preReleaseMint(address recipient) public returns (uint256) {
require(remainingPreReleaseMints[msg.sender] > 0, "you have 0 remaining pre-release mints");
remainingPreReleaseMints[msg.sender] = remainingPreReleaseMints[msg.sender] - 1;
require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one");
_tokensMinted.increment();
uint256 newTokenId = _tokensMinted.current();
uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();
_mint(recipient, newTokenId);
tokenIdToMetadataId[newTokenId] = metadataId;
emit mintEvent(recipient, newTokenId, metadataId);
return newTokenId;
}
// Mint multiple free Voxmon
function preReleaseMint(address recipient, uint256 numberToMint) public returns (uint256[] memory) {
require(remainingPreReleaseMints[msg.sender] >= numberToMint, "You don\'t have enough remaining pre-release mints");
uint256[] memory tokenIdsMinted = new uint256[](numberToMint);
for(uint i = 0; i < numberToMint; i++) {
tokenIdsMinted[i] = preReleaseMint(recipient);
}
return tokenIdsMinted;
}
// Re-Roll a Voxmon
// Cost is 0.01 ether
function reroll(uint256 tokenId) payable public returns (uint256) {
require(ownerOf(tokenId) == msg.sender, "you must own this token to reroll");
require(msg.value >= REROLL_COST, "not enough ether, rerolling costs 0.03 ether");
require(tokenIdToFrozenForArt[tokenId] == false, "this token is frozen");
_tokensRerolled.increment();
uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current();
tokenIdToMetadataId[tokenId] = newMetadataId;
emit rerollEvent(msg.sender, tokenId, newMetadataId);
return newMetadataId;
}
// Re-Roll a Voxmon
// Cost is 0.01 ether
function freeReroll(uint256 tokenId) public returns (uint256) {
require(remainingRerolls[msg.sender] > 0, "you have 0 remaining free rerolls");
remainingRerolls[msg.sender] = remainingRerolls[msg.sender] - 1;
require(ownerOf(tokenId) == msg.sender, "you must own the token to reroll");
require(tokenIdToFrozenForArt[tokenId] == false, "this token is frozen");
_tokensRerolled.increment();
uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current();
tokenIdToMetadataId[tokenId] = newMetadataId;
emit rerollEvent(msg.sender, tokenId, newMetadataId);
return newMetadataId;
}
}
// 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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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);
} | Withdraw funds in contract for security, can only be sent to owner (or should we allow anyone to withdraw?) | function withdraw(uint _amount) external onlyOwner {
address payable receiver = payable(owner());
receiver.transfer(_amount);
}
| 6,156,510 |
// ....................
// ................................
// ....... ...........
// .... / .........
// .... ,(// ........
// ... (( (//// .......
// .. (( .((//// .......
// .. ((, ((////// .. ......
// . ##, .(((///// .. ......
// . ### ((/(///// ... .....
// . ### (((( (//// .... .....
// ### (( .(((( //// .... .....
// . ###, ((( (((( //// /. ... .....
// ### (((( /(((( (//( //, ... * .....
// /### *(((((((( ((// //// .. * .....
// /### .((((((( (((( /////. . * ....
// .#### #((((( ((((. /////// * ....
// ####. ,(#((( ((((/( .////*////* * ...
// ####. ,(#(( (((/////////// ////* ** ....
// ,####( #((# /((////////* ///// ** ....
// ##### *((( .. ///// **, ....
// ###### (( ////* .*** ...
// (####(( /////.**** ...
// (#((((((, .////////*/, ...
// *((((((((((((((((///////////*. ...
// ((((((((((////////. ...
// ..
// ..
//
//
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
BurningMoon differentiates between Buys/Sells/Transfers
to apply different taxes/Limits to the transfer.
This can be abused to disable sells to create a Honeypot.
Burning Moon also locks you from selling/transfering for 2 hours after each Transfer.
Rugscreens will rightfully warn you about that.
Also, BurningMoon includes a Liquidity lock function that can release the liquidity once the Lock
time is over.
Please DYOR
The Contract starts at Line 818.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
BurningMoon is a Hyper Deflationary Token.
There is an initial supply of 100.000.000 Token,
the goal is to reduce the supply to less than 21.000.000 Token(Bitcoin max. Supply)
BurningMoon implements a variable tax capped to 20%.
To burn a maximum amount of tokens, the start tax will be 36% for buys/transfers until the first change.
Each transaction 3 things Happen:
Burn:
Burning Moon Burns clean and without residue.
Tokens will not just land in a burn-wallet (or worse, Vitaliks Wallet),
they will be completely removed from existance.
Auto Liquidity:
A Massive Burn requires enough liquidity to control the Burn.
That way everyone can sell their BurningMoon without worrying about price impact.
BNB-Autostaking:
Automatically stake for BNB.
Claimable at any time.
A part of the autostaking BNB will be used for Marketing.
Whale Protection:
Any Buy/Transfer where the recipient would recieve more than 1% of the supply will be declined.
Dump Protection:
Any Sell over 0.05% of the total supply gets declined.
Sellers get locked from selling/transfering for 2 hours after selling.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IPancakeERC20 {
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;
}
interface IPancakeFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IPancakeRouter01 {
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function factory() external pure returns (address);
function WETH() external pure returns (address);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IPancakeRouter02 is IPancakeRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() 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 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);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Burning Moon Contract ////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
contract BurningMoon is IBEP20, Ownable
{
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => uint256) private _sellLock;
EnumerableSet.AddressSet private _excluded;
EnumerableSet.AddressSet private _whiteList;
EnumerableSet.AddressSet private _excludedFromSellLock;
EnumerableSet.AddressSet private _excludedFromStaking;
//Token Info
string private constant _name = 'BurningTest';
string private constant _symbol = 'But';
uint8 private constant _decimals = 9;
uint256 public constant InitialSupply= 100 * 10**6 * 10**_decimals;//equals 100.000.000 token
//Divider for the MaxBalance based on circulating Supply (1%)
uint8 public constant BalanceLimitDivider=100;
//Divider for the Whitelist MaxBalance based on initial Supply(0.2%)
uint16 public constant WhiteListBalanceLimitDivider=500;
//Divider for sellLimit based on circulating Supply (0.05%)
uint16 public constant SellLimitDivider=2000;
//Sellers get locked for MaxSellLockTime so they can't dump repeatedly
uint16 public constant MaxSellLockTime= 2 hours;
//TODO: Change to 7 days
//The time Liquidity gets locked at start and prolonged once it gets released
uint256 private constant DefaultLiquidityLockTime=1 hours;
//The Team Wallet is a Multisig wallet that reqires 3 signatures for each action
address public constant TeamWallet=0x921Ff3A7A6A3cbdF3332781FcE03d2f4991c7868;
//TODO: Change to Mainnet
//TestNet
address private constant PancakeRouter=0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;
//MainNet
//address private constant PancakeRouter=0x10ED43C718714eb63d5aA57B78B54704E256024E;
//variables that track balanceLimit and sellLimit,
//can be updated based on circulating supply and Sell- and BalanceLimitDividers
uint256 private _circulatingSupply =InitialSupply;
uint256 public balanceLimit = _circulatingSupply;
uint256 public sellLimit = _circulatingSupply;
//Limits max tax, only gets applied for tax changes, doesn't affect inital Tax
uint8 public constant MaxTax=20;
//Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer
uint8 private _buyTax;
uint8 private _sellTax;
uint8 private _transferTax;
uint8 private _burnTax;
uint8 private _liquidityTax;
uint8 private _stakingTax;
address private _pancakePairAddress;
IPancakeRouter02 private _pancakeRouter;
//modifier for functions only the team can call
modifier onlyTeam() {
require(_isTeam(msg.sender), "Caller not in Team");
_;
}
//Checks if address is in Team, is needed to give Team access even if contract is renounced
//Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks)
function _isTeam(address addr) private view returns (bool){
return addr==owner()||addr==TeamWallet;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Constructor///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor () {
//contract creator 90% of the token to create LP-Pair
uint256 deployerBalance=_circulatingSupply*9/10;
_balances[msg.sender] = deployerBalance;
emit Transfer(address(0), msg.sender, deployerBalance);
//contract gets 10% of the token to generate LP token and Marketing Budget fase
//contract will sell token over the first 200 sells to generate maximum LP and BNB
uint256 injectBalance=_circulatingSupply-deployerBalance;
_balances[address(this)]=injectBalance;
emit Transfer(address(0), address(this),injectBalance);
// Pancake Router
_pancakeRouter = IPancakeRouter02(PancakeRouter);
//Creates a Pancake Pair
_pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH());
//Sets Buy/Sell limits
balanceLimit=InitialSupply/BalanceLimitDivider;
sellLimit=InitialSupply/SellLimitDivider;
//Sets sellLockTime to be max by default
sellLockTime=MaxSellLockTime;
//Set Starting Tax to very high percentage(36%) to achieve maximum burn in the beginning
//as in the beginning there is the highest token volume
//any change in tax rate needs to be below maxTax(20%)
_buyTax=36;
_sellTax=20;//Sell Tax is lower, as otherwise slippage would be too high to sell
_transferTax=36;
//97% gets burned
_burnTax=97;
//a small percentage gets added to the Contract token as 10% of token are already injected to
//be converted to LP and MarketingBNB
_liquidityTax=2;
_stakingTax=1;
//Team wallet and deployer are excluded from Taxes
_excluded.add(TeamWallet);
_excluded.add(msg.sender);
//excludes Pancake Router, pair, contract and burn address from staking
_excludedFromStaking.add(address(_pancakeRouter));
_excludedFromStaking.add(_pancakePairAddress);
_excludedFromStaking.add(address(this));
_excludedFromStaking.add(0x000000000000000000000000000000000000dEaD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Transfer functionality////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//transfer function, every transfer runs through this function
function _transfer(address sender, address recipient, uint256 amount) private{
require(sender != address(0), "Transfer from zero");
require(recipient != address(0), "Transfer to zero");
//Manually Excluded adresses are transfering tax and lock free
bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient));
//Transactions from and to the contract are always tax and lock free
bool isContractTransfer=(sender==address(this) || recipient==address(this));
//transfers between PancakeRouter and PancakePair are tax and lock free
address pancakeRouter=address(_pancakeRouter);
bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter)
|| (recipient == _pancakePairAddress && sender == pancakeRouter));
//differentiate between buy/sell/transfer to apply different taxes/restrictions
bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter;
bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter;
//Pick transfer
if(isContractTransfer || isLiquidityTransfer || isExcluded){
_feelessTransfer(sender, recipient, amount);
}
else{
//once trading is enabled, it can't be turned off again
require(tradingEnabled,"trading not yet enabled");
if(whiteListTrading){
_whiteListTransfer(sender,recipient,amount,isBuy,isSell);
}
else{
_taxedTransfer(sender,recipient,amount,isBuy,isSell);
}
}
}
//if whitelist is active, all taxed transfers run through this
function _whiteListTransfer(address sender, address recipient,uint256 amount,bool isBuy,bool isSell) private{
//only apply whitelist restrictions during buys and transfers
if(!isSell){
//the recipient needs to be on Whitelist. Works for both buys and transfers.
//transfers to other whitelisted addresses are allowed.
require(_whiteList.contains(recipient),"recipient not on whitelist");
//Limit is 1/500 of initialSupply during whitelist, to allow for a large whitelist without causing a massive
//price impact of the whitelist
require((_balances[recipient]+amount<=InitialSupply/WhiteListBalanceLimitDivider),"amount exceeds whitelist max");
}
_taxedTransfer(sender,recipient,amount,isBuy,isSell);
}
//applies taxes, checks for limits, locks generates autoLP and stakingBNB, and autostakes
function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{
uint256 recipientBalance = _balances[recipient];
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
uint8 tax;
if(isSell){
if(!_excludedFromSellLock.contains(sender)){
//If seller sold less than sellLockTime(2h) ago, sell is declined, can be disabled by Team
require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock");
//Sets the time sellers get locked(2 hours by default)
_sellLock[sender]=block.timestamp+sellLockTime;
}
//Sells can't exceed the sell limit(50.000 Tokens at start, can be updated to circulating supply)
require(amount<=sellLimit,"Dump protection");
tax=_sellTax;
} else if(isBuy){
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
require(recipientBalance+amount<=balanceLimit,"whale protection");
tax=_buyTax;
} else {//Transfer
//withdraws BNB when sending less or equal to 1 Token
//that way you can withdraw without connecting to any dApp.
//might needs higher gas limit
if(amount<=10**(_decimals)) withdrawBNB(sender);
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
require(recipientBalance+amount<=balanceLimit,"whale protection");
//Transfers are disabled in sell lock, this doesn't stop someone from transfering before
//selling, but there is no satisfying solution for that, and you would need to pax additional tax
if(!_excludedFromSellLock.contains(sender))
require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock");
tax=_transferTax;
}
//Swapping AutoLP and MarketingBNB is only possible if sender is not pancake pair,
//if its not manually disabled, if its not already swapping and if its a Sell to avoid
// people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens
if((sender!=_pancakePairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell)
_swapContractToken();
//Calculates the exact token amount for each tax
uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax);
//staking and liquidity Tax get treated the same, only during conversion they get split
uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax);
//Subtract the Taxed Tokens from the amount
uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken);
//Removes token and handles staking
_removeToken(sender,amount);
//Adds the taxed tokens to the contract wallet
_balances[address(this)] += contractToken;
//Burns tokens
_circulatingSupply-=tokensToBeBurnt;
//Adds token and handles staking
_addToken(recipient, taxedAmount);
emit Transfer(sender,recipient,taxedAmount);
}
//Feeless transfer only transfers and autostakes
function _feelessTransfer(address sender, address recipient, uint256 amount) private{
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
//Removes token and handles staking
_removeToken(sender,amount);
//Adds token and handles staking
_addToken(recipient, amount);
emit Transfer(sender,recipient,amount);
}
//Calculates the token that should be taxed
function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) {
return (amount*tax*taxPercent) / 10000;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//BNB Autostake/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Autostake uses the balances of each holder to redistribute auto generated BNB.
//Each transaction _addToken and _removeToken gets called for the transaction amount
//WithdrawBNB can be used for any holder to withdraw BNB at any time, like true Staking,
//so unlike MRAT clones you can leave and forget your Token and claim after a while
//lock for the withdraw
bool private _isWithdrawing;
//Multiplier to add some accuracy to profitPerShare
uint256 private constant DistributionMultiplier = 2**64;
//profit for each share a holder holds, a share equals a token.
uint256 public profitPerShare;
//the total reward distributed through staking, for tracking purposes
uint256 public totalStakingReward;
//the total payout through staking, for tracking purposes
uint256 public totalPayouts;
//marketing share starts at 80% to push initial marketing, after start
//its capped to 50% max, the percentage of the staking that gets used for
//marketing/paying the team
uint8 public marketingShare=80;
//balance that is claimable by the team
uint256 public marketingBalance;
//Mapping of the already paid out(or missed) shares of each staker
mapping(address => uint256) private alreadyPaidShares;
//Mapping of shares that are reserved for payout
mapping(address => uint256) private toBePaid;
//Contract, pancake and burnAddress are excluded, other addresses like CEX
//can be manually excluded, excluded list is limited to 30 entries to avoid a
//out of gas exeption during sells
function isExcludedFromStaking(address addr) public view returns (bool){
return _excludedFromStaking.contains(addr);
}
//Total shares equals circulating supply minus excluded Balances
function _getTotalShares() public view returns (uint256){
uint256 shares=_circulatingSupply;
//substracts all excluded from shares, excluded list is limited to 30
// to avoid creating a Honeypot through OutOfGas exeption
for(uint i=0; i<_excludedFromStaking.length(); i++){
shares-=_balances[_excludedFromStaking.at(i)];
}
return shares;
}
//adds Token, adds new BNB to the toBePaid mapping and resets staking
function _addToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]+amount;
if(isExcludedFromStaking(addr)){
_balances[addr]=newAmount;
return;
}
//gets the payout before the change
uint256 payment=_newDividentsOf(addr);
//resets dividents to 0 for newAmount
alreadyPaidShares[addr] = profitPerShare * newAmount;
//adds dividents to the toBePaid mapping
toBePaid[addr]+=payment;
//sets newBalance
_balances[addr]=newAmount;
}
//removes Token, adds BNB to the toBePaid mapping and resets staking
function _removeToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]-amount;
if(isExcludedFromStaking(addr)){
_balances[addr]=newAmount;
return;
}
//gets the payout before the change
uint256 payment=_newDividentsOf(addr);
//sets newBalance
_balances[addr]=newAmount;
//resets dividents to 0 for newAmount
alreadyPaidShares[addr] = profitPerShare * newAmount;
//adds dividents to the toBePaid mapping
toBePaid[addr]+=payment;
}
//gets the not dividents of a staker that aren't in the toBePaid mapping
//returns wrong value for excluded accounts
function _newDividentsOf(address staker) private view returns (uint256) {
uint256 fullPayout = profitPerShare * _balances[staker];
// if theres an overflow for some unexpected reason, return 0, instead of
// an exeption to still make trades possible
if(fullPayout<alreadyPaidShares[staker]) return 0;
return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier;
}
//distributes bnb between marketing share and dividents
function _distributeStake(uint256 BNBamount) private {
// Deduct marketing Tax
uint256 marketingSplit = (BNBamount * marketingShare) / 100;
uint256 amount = BNBamount - marketingSplit;
marketingBalance+=marketingSplit;
if (amount > 0) {
totalStakingReward += amount;
uint256 totalShares=_getTotalShares();
//when there are 0 shares, add everything to marketing budget
if (totalShares == 0) {
marketingBalance += amount;
}else{
//Increases profit per share based on current total shares
profitPerShare += ((amount * DistributionMultiplier) / totalShares);
}
}
}
event OnWithdrawBNB(uint256 amount, address recipient);
//withdraws all dividents of address
function withdrawBNB(address addr) private{
require(!_isWithdrawing);
_isWithdrawing=true;
uint256 amount;
if(isExcludedFromStaking(addr)){
//if excluded just withdraw remaining toBePaid BNB
amount=toBePaid[addr];
toBePaid[addr]=0;
}
else{
uint256 newAmount=_newDividentsOf(addr);
//sets payout mapping to current amount
alreadyPaidShares[addr] = profitPerShare * _balances[addr];
//the amount to be paid
amount=toBePaid[addr]+newAmount;
toBePaid[addr]=0;
}
totalPayouts+=amount;
(bool sent,) =addr.call{value: (amount)}("");
require(sent,"withdraw failed");
emit OnWithdrawBNB(amount, addr);
_isWithdrawing=false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Swap Contract Tokens//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//tracks auto generated BNB, useful for ticker etc
uint256 public totalLPBNB;
//Locks the swap if already swapping
bool private _isSwappingContractModifier;
modifier lockTheSwap {
_isSwappingContractModifier = true;
_;
_isSwappingContractModifier = false;
}
//swaps the token on the contract for Marketing BNB and LP Token.
//always swaps the sellLimit of token to avoid a large price impact
function _swapContractToken() private lockTheSwap{
uint256 contractBalance=_balances[address(this)];
uint16 totalTax=_liquidityTax+_stakingTax;
uint256 tokenToSwap=sellLimit;
//only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0
if(contractBalance<tokenToSwap||totalTax==0){
return;
}
//splits the token in TokenForLiquidity and tokenForMarketing
uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax;
uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity;
//splits tokenForLiquidity in 2 halves
uint256 liqToken=tokenForLiquidity/2;
uint256 liqBNBToken=tokenForLiquidity-liqToken;
//swaps marktetingToken and the liquidity token half for BNB
uint256 swapToken=liqBNBToken+tokenForMarketing;
//Gets the initial BNB balance, so swap won't touch any staked BNB
uint256 initialBNBBalance = address(this).balance;
_swapTokenForBNB(swapToken);
uint256 newBNB=(address(this).balance - initialBNBBalance);
//calculates the amount of BNB belonging to the LP-Pair and converts them to LP
uint256 liqBNB = (newBNB*liqBNBToken)/swapToken;
_addLiquidity(liqToken, liqBNB);
//Get the BNB balance after LP generation to get the
//exact amount of token left for Staking
uint256 distributeBNB=(address(this).balance - initialBNBBalance);
//distributes remaining BNB between stakers and Marketing
_distributeStake(distributeBNB);
}
//swaps tokens on the contract for BNB
function _swapTokenForBNB(uint256 amount) private {
_approve(address(this), address(_pancakeRouter), amount);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _pancakeRouter.WETH();
_pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this),
block.timestamp
);
}
//Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner)
function _addLiquidity(uint256 tokenamount, uint256 bnbamount) private {
totalLPBNB+=bnbamount;
_approve(address(this), address(_pancakeRouter), tokenamount);
_pancakeRouter.addLiquidityETH{value: bnbamount}(
address(this),
tokenamount,
0,
0,
address(this),
block.timestamp
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//public functions /////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
function getLiquidityReleaseTimeInSeconds() public view returns (uint256){
if(block.timestamp<_liquidityUnlockTime){
return _liquidityUnlockTime-block.timestamp;
}
return 0;
}
function getBurnedTokens() public view returns(uint256){
return (InitialSupply-_circulatingSupply)/10**_decimals;
}
function getLimits() public view returns(uint256 balance, uint256 sell){
return(balanceLimit/10**_decimals, sellLimit/10**_decimals);
}
function getTaxes() public view returns(uint256 burnTax,uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){
return (_burnTax,_liquidityTax,_stakingTax,_buyTax,_sellTax,_transferTax);
}
function getWhitelistedStatus(address AddressToCheck) public view returns(bool){
return _whiteList.contains(AddressToCheck);
}
//How long is a given address still locked from selling
function getAddressSellLockTimeInSeconds(address AddressToCheck) public view returns (uint256){
uint256 lockTime=_sellLock[AddressToCheck];
if(lockTime<=block.timestamp)
{
return 0;
}
return lockTime-block.timestamp;
}
function getSellLockTimeInSeconds() public view returns(uint256){
return sellLockTime;
}
//Functions every wallet can call
//Resets sell lock of caller to the default sellLockTime should something go very wrong
function AddressResetSellLock() public{
_sellLock[msg.sender]=block.timestamp+sellLockTime;
}
//withdraws dividents of sender
function AddressWithdraw() public{
withdrawBNB(msg.sender);
}
function getDividents(address addr) public view returns (uint256){
if(isExcludedFromStaking(addr)) return toBePaid[addr];
return _newDividentsOf(addr)+toBePaid[addr];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Settings//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public sellLockDisabled;
uint256 public sellLockTime;
bool public manualConversion;
//Excludes account from Staking
function TeamExcludeFromStaking(address addr) public onlyTeam{
//a long exluded list could lead to a Honeypot, therefore limit entries
require(_excludedFromStaking.length()<30);
require(!isExcludedFromStaking(addr));
uint256 newDividents=_newDividentsOf(addr);
alreadyPaidShares[addr]=_balances[addr]*profitPerShare;
toBePaid[addr]+=newDividents;
_excludedFromStaking.add(addr);
}
//Includes excluded Account to staking
function TeamIncludeToStaking(address addr) public onlyTeam{
require(isExcludedFromStaking(addr));
_excludedFromStaking.remove(addr);
//sets alreadyPaidShares to the current amount
alreadyPaidShares[addr]=_balances[addr]*profitPerShare;
}
function TeamWithdrawMarketingBNB() public onlyTeam{
uint256 amount=marketingBalance;
marketingBalance=0;
(bool sent,) =TeamWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
function TeamWithdrawMarketingBNB(uint256 amount) public onlyTeam{
require(amount<=marketingBalance);
marketingBalance-=amount;
(bool sent,) =TeamWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
//switches autoLiquidity and marketing BNB generation during transfers
function TeamSwitchManualBNBConversion(bool manual) public onlyTeam{
manualConversion=manual;
}
//Disables the timeLock after selling for everyone
function TeamDisableSellLock(bool disabled) public onlyTeam{
sellLockDisabled=disabled;
}
//Sets SellLockTime, needs to be lower than MaxSellLockTime
function TeamSetSellLockTime(uint8 sellLockMinutes)public onlyTeam{
uint256 newSellLockTime= sellLockMinutes*60;
require(newSellLockTime<=MaxSellLockTime,"Sell Lock time too high");
sellLockTime=newSellLockTime;
}
//Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot
function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{
uint8 totalTax=burnTaxes+liquidityTaxes+stakingTaxes;
require(totalTax==100, "burn+liq+marketing needs to equal 100%");
require(buyTax<=MaxTax&&sellTax<=MaxTax&&transferTax<=MaxTax,"taxes higher than max tax");
_burnTax=burnTaxes;
_liquidityTax=liquidityTaxes;
_stakingTax=stakingTaxes;
_buyTax=buyTax;
_sellTax=sellTax;
_transferTax=transferTax;
}
//How much of the staking tax should be allocated for marketing
function TeamChangeMarketingShare(uint8 newShare) public onlyTeam{
require(newShare<=50);
marketingShare=newShare;
}
//manually converts contract token to LP and staking BNB
function TeamCreateLPandBNB() public onlyTeam{
_swapContractToken();
}
//Exclude/Include account from fees (eg. CEX)
function TeamExcludeAccountFromFees(address account) public onlyTeam {
_excluded.add(account);
}
function TeamIncludeAccountToFees(address account) public onlyTeam {
_excluded.remove(account);
}
//Exclude/Include account from fees (eg. CEX)
function TeamExcludeAccountFromSellLock(address account) public onlyTeam {
_excludedFromSellLock.add(account);
}
function TeamIncludeAccountToSellLock(address account) public onlyTeam {
_excludedFromSellLock.remove(account);
}
//Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot)
function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{
//SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP
require(newSellLimit<_circulatingSupply/100);
//Adds decimals to limits
newBalanceLimit=newBalanceLimit*10**_decimals;
newSellLimit=newSellLimit*10**_decimals;
//Calculates the target Limits based on supply
uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider;
uint256 targetSellLimit=_circulatingSupply/SellLimitDivider;
require((newBalanceLimit>=targetBalanceLimit),
"newBalanceLimit needs to be at least target");
require((newSellLimit>=targetSellLimit),
"newSellLimit needs to be at least target");
balanceLimit = newBalanceLimit;
sellLimit = newSellLimit;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup Functions///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public tradingEnabled;
bool public whiteListTrading;
address private _liquidityTokenAddress;
//Enables whitelist trading and locks Liquidity for a short time
function SetupEnableWhitelistTrading() public onlyTeam{
require(!tradingEnabled);
//Sets up the excluded from staking list
tradingEnabled=true;
whiteListTrading=true;
//Liquidity gets locked for 7 days at start, needs to be prolonged once
//start is successful
_liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
}
//Enables trading for everyone
function SetupEnableTrading() public onlyTeam{
require(tradingEnabled&&whiteListTrading);
whiteListTrading=false;
}
//Sets up the LP-Token Address required for LP Release
function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyTeam{
_liquidityTokenAddress=liquidityTokenAddress;
}
//Functions for whitelist
function SetupAddToWhitelist(address addressToAdd) public onlyTeam{
_whiteList.add(addressToAdd);
}
function SetupAddArrayToWhitelist(address[] memory addressesToAdd) public onlyTeam{
for(uint i=0; i<addressesToAdd.length; i++){
_whiteList.add(addressesToAdd[i]);
}
}
function SetupRemoveFromWhitelist(address addressToRemove) public onlyTeam{
_whiteList.remove(addressToRemove);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Liquidity Lock////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//the timestamp when Liquidity unlocks
uint256 private _liquidityUnlockTime;
//Sets Liquidity Release to 20% at a time and prolongs liquidity Lock for a Week after Release.
//Should be called once start was successful.
bool public liquidityRelease20Percent;
function TeamlimitLiquidityReleaseTo20Percent() public onlyTeam{
liquidityRelease20Percent=true;
}
//Sets the Liquidity Lock, can only be prolonged
function TeamUnlockLiquidityInDays(uint16 daysUntilUnlock) public onlyTeam{
_prolongLiquidityLock(daysUntilUnlock*(1 days));
}
function TeamUnlockLiquidityInSeconds(uint16 secondsUntilUnlock) public onlyTeam{
_prolongLiquidityLock(secondsUntilUnlock);
}
function _prolongLiquidityLock(uint256 newUnlockTime) private{
// require new unlock time to be longer than old one
require(newUnlockTime>_liquidityUnlockTime);
_liquidityUnlockTime=newUnlockTime;
}
//Release Liquidity Tokens once unlock time is over
function TeamReleaseLiquidity() public onlyTeam {
//Only callable if liquidity Unlock time is over
require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
IPancakeERC20 liquidityToken = IPancakeERC20(_liquidityTokenAddress);
uint256 amount = liquidityToken.balanceOf(address(this));
if(liquidityRelease20Percent)
{
_liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
//regular liquidity release, only releases 20% at a time and locks liquidity for another week
amount=amount*2/10;
liquidityToken.transfer(TeamWallet, amount);
}
else
{
//Liquidity release if something goes wrong at start
//liquidityRelease20Percent should be called once everything is clear
liquidityToken.transfer(TeamWallet, amount);
}
}
//Removes Liquidity once unlock Time is over,
function TeamRemoveLiquidity(bool addToStaking) public onlyTeam {
//Only callable if liquidity Unlock time is over
require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
_liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
IPancakeERC20 liquidityToken = IPancakeERC20(_liquidityTokenAddress);
uint256 amount = liquidityToken.balanceOf(address(this));
if(liquidityRelease20Percent){
amount=amount*2/10; //only remove 20% each
}
liquidityToken.approve(address(_pancakeRouter),amount);
//Removes Liquidity and either distributes liquidity BNB to stakers, or
// adds them to marketing Balance
//Token will be converted
//to Liquidity and Staking BNB again
uint256 initialBNBBalance = address(this).balance;
_pancakeRouter.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this),
amount,
0,
0,
address(this),
block.timestamp
);
uint256 newBNBBalance = address(this).balance-initialBNBBalance;
if(addToStaking){
_distributeStake(newBNBBalance);
}
else{
marketingBalance+=newBNBBalance;
}
}
//Releases all remaining BNB on the contract wallet, so BNB wont be burned
//Can only be called 30 days after Liquidity unlocks
function TeamRemoveRemainingBNB() public onlyTeam{
require(block.timestamp >= _liquidityUnlockTime+30 days, "Not yet unlocked");
_liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
(bool sent,) =TeamWallet.call{value: (address(this).balance)}("");
require(sent);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//external//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
receive() external payable {}
fallback() external payable {}
// IBEP20
function getOwner() external view override returns (address) {
return owner();
}
function name() external pure override returns (string memory) {
return _name;
}
function symbol() external pure override returns (string memory) {
return _symbol;
}
function decimals() external pure override returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _circulatingSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address _owner, address spender) external view override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "Approve from zero");
require(spender != address(0), "Approve to zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "Transfer > allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
// IBEP20 - Helpers
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "<0 allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
} | Enables whitelist trading and locks Liquidity for a short timeSets up the excluded from staking listLiquidity gets locked for 7 days at start, needs to be prolonged oncestart is successful | function SetupEnableWhitelistTrading() public onlyTeam{
require(!tradingEnabled);
tradingEnabled=true;
whiteListTrading=true;
_liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
}
| 12,999,095 |
./partial_match/1/0x257EE57e3b15D1F271AcF92A041Aa16aA25fce9f/sources/KYLTokenSwap.sol | Lock KYLv1 Send same amount KYLv2 | function Swap_KYLV1_to_KYLV2(uint256 amount) public nonReentrant {
address sender = _msgSender();
ERC20(kylV1).transferFrom(sender, kylV1Treasure, amount);
ERC20(kylV2).transferFrom(kylV2Treasure, sender, amount);
emit Swap_KYL(sender, amount);
}
| 16,072,506 |
pragma solidity ^0.4.24;
/*
* @title: Verified Token Controller
* Verification management for token owner
* Setting initial number of confirmations required for each/any type of registry, adding or removing them.
* Created on 2018-04-26, by Blockchain Labs, NZ
*/
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/IRegistry.sol";
import "./interfaces/IController.sol";
import "./Attributes.sol";
contract Controller is IController, Attributes, Ownable {
/*
* @notice: authorities that trusted by token issuer
*/
IRegistry[] public registries;
/*
* @notice: attribute key and value are stored in 'pairs'
*/
struct pairs {
bytes32 attribute;
bytes32 value;
}
pairs[] private receiverRequirements;
pairs[] private senderRequirements;
/*
* @dev: if zero, no checks will be performed
*/
uint256 private confirmationsRequired;
event RequiredConfirmationsUpdated(
uint256 confirmations,
uint updatedAt
);
event RequiredDataUpdated(
bytes32 indexed key,
bytes32 indexed value,
uint updatedAt
);
event AcceptedRegistriesUpdated(
IRegistry[] registries,
uint updatedAt
);
/*
* @dev: Contract owner must set up registry(ies) to use
*/
constructor(IRegistry[] _registries, uint256 _confirmationsRequired) public {
confirmationsRequired = _confirmationsRequired;
updateRegistries(_registries);
}
/*
* @notice: Owner can add, delete or update the number of confirmations required for each registry
* @dev: adding addresses one by one is chosen, because of Solidity (for now) doesn't check
* @dev: if the list of addresses is the list of contracts.
*/
function updateRegistries(IRegistry[] _registries) public onlyOwner {
IRegistry[] memory contracts = new IRegistry[](_registries.length);
IRegistry currentRegistry;
for (uint256 i = 0; i < _registries.length; i++) {
currentRegistry = IRegistry(_registries[i]);
require(isContract(currentRegistry));
require(currentRegistry.hasAttribute(currentRegistry, REGISTRY_TYPE));
contracts[i] = currentRegistry;
}
registries = contracts;
emit AcceptedRegistriesUpdated(contracts, now);
}
/*
* @notice: Owner can add, delete or update the number of confirmations required for each registry
*/
function updateRequiredConfirmations(uint256 _confirmationsRequired) public onlyOwner {
confirmationsRequired = _confirmationsRequired;
emit RequiredConfirmationsUpdated(_confirmationsRequired, now);
}
/*
* @notice: Owner can add, delete or update Receiver requirements
*/
function updateReceiverRequirements(bytes32[] _attributes, bytes32[] _values) public onlyOwner {
uint256 pairsNumber = _attributes.length;
require( pairsNumber == _values.length);
pairs memory newPair;
receiverRequirements.length = 0;
if (pairsNumber == 0)
emit ReceiverRequirementsUpdated("no requirements", "no requirements", now);
for (uint256 i = 0; i < pairsNumber; i++) {
newPair.attribute = _attributes[i];
newPair.value =_values[i];
receiverRequirements.push(newPair);
emit ReceiverRequirementsUpdated(_attributes[i], _values[i], now);
}
}
/*
* @notice: Owner can add, delete or update Sender requirements
*/
function updateSenderRequirements(bytes32[] _attributes, bytes32[] _values) public onlyOwner{
uint256 pairsNumber = _attributes.length;
require( pairsNumber == _values.length);
pairs memory newPair;
senderRequirements.length = 0;
if (pairsNumber == 0)
emit SenderRequirementsUpdated("no requirements", "no requirements", now);
for (uint256 i = 0; i < pairsNumber; i++) {
newPair.attribute = _attributes[i];
newPair.value =_values[i];
senderRequirements.push(newPair);
emit SenderRequirementsUpdated(_attributes[i], _values[i], now);
}
}
/*
* @dev: checks if token transfer is allowed
*/
function isTransferAllowed(address _receiver, address _sender) public view returns(bool) {
if(confirmationsRequired != 0) {
require(isVerified(_sender, senderRequirements), "Sender has not been authorized to send tokens");
require(isVerified(_receiver, receiverRequirements), "Receiver was not verified");
}
return true;
}
/*
* @dev: checks if Receiver is verified
*/
function isReceiverVerified(address _address) public view returns(bool) {
return isVerified(_address, receiverRequirements);
}
/*
* @dev: checks if Receiver is verified
*/
function isSenderVerified(address _address) public view returns(bool) {
return isVerified(_address, senderRequirements);
}
/*
* @dev: checks if the address from appropriate requirements list has attribute=>value pair in the registry
*/
function isVerified(address _address, pairs[] requirements) internal view returns(bool) {
if(requirements.length == 0)
return false;
uint256 pairsToConfirm = requirements.length;
uint256 pairsConfirmed;
uint256 registriesConfirmed;
IRegistry registry;
pairs memory currentPair;
for(uint256 i = 0; i < registries.length; i++) {
registry = IRegistry(registries[i]);
pairsConfirmed = 0;
for(uint256 j = 0; j < pairsToConfirm; j++) {
currentPair = requirements[j];
if(registry.verify(_address, currentPair.attribute, currentPair.value))
pairsConfirmed++;
}
if (pairsConfirmed >= pairsToConfirm)
registriesConfirmed++;
if (registriesConfirmed >= confirmationsRequired)
return true;
}
return false;
}
/*
* @dev: checks if an address is the contract address
*/
function isContract(address addr) public view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
/*
* @dev: return the number of confirmations required for successful transfer
*/
function getNumberOfConfirmationsRequired() public view returns (uint) {
return confirmationsRequired;
}
/*
* @dev: return the pairs (attribute=>value) required for Receiver in order to transfer tokens
*/
function getReceiverRequirements() public view returns (bytes32[], bytes32[]) {
uint256 numberOfPairs = receiverRequirements.length;
if (numberOfPairs != 0) {
bytes32[] memory attributes = new bytes32[](numberOfPairs);
bytes32[] memory values = new bytes32[](numberOfPairs);
for(uint i = 0; i < receiverRequirements.length; i++) {
attributes[i] = receiverRequirements[i].attribute;
values[i] = receiverRequirements[i].value;
}
}
return (attributes, values);
}
/*
* @dev: return the pairs (attribute=>value) required for Sender in order to transfer tokens
*/
function getSenderRequirements() public view returns (bytes32[], bytes32[]) {
uint256 numberOfPairs = senderRequirements.length;
if (numberOfPairs != 0) {
bytes32[] memory attributes = new bytes32[](numberOfPairs);
bytes32[] memory values = new bytes32[](numberOfPairs);
for(uint i = 0; i < senderRequirements.length; i++) {
attributes[i] = senderRequirements[i].attribute;
values[i] = senderRequirements[i].value;
}
}
return (attributes, values);
}
/*
* @dev: return list of registries that assigned by Token Issuer to verify token transfers
*/
function getRegistries() public view returns (IRegistry[]) {
return registries;
}
} | : checks if Receiver is verified/ | function isSenderVerified(address _address) public view returns(bool) {
return isVerified(_address, senderRequirements);
}
| 905,263 |
./full_match/1/0x093f6dFaD3c1C29A21CC8A88a8a5eD5A2A67d7B8/sources/Volumes/Data/Projects/Less/lessswap-contracts/contracts/libraries/LessSwapLibrary.sol | performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "LessSwapLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(
factory,
path[i],
path[i + 1]
);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 4,866,854 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Burnable.sol";
import "./ERC721Pausable.sol";
import "./AccessControlEnumerable.sol";
import "./Context.sol";
import "./Counters.sol";
import "./SniftieUtils.sol";
import "./Ownable.sol";
contract SniftieERC721Common is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable, Ownable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter private _tokenIdTracker;
mapping(string => uint8) hashes;
string private _baseTokenURI;
string private _contractMetadataURI;
mapping (uint256 => string) private _tokenURIs;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
constructor(string memory name, string memory symbol, string memory baseTokenURI, string memory contractMetadataURI, address sniftieAdmin) ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
_contractMetadataURI = contractMetadataURI;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(DEFAULT_ADMIN_ROLE, sniftieAdmin);
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(MINTER_ROLE, sniftieAdmin);
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, sniftieAdmin);
}
function contractURI() public view returns (string memory) {
return _contractMetadataURI;
}
function setContractMetadataURI(string memory contractMetadataURI) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Must have DEFAULT_ADMIN_ROLE to set contract metadata uri");
_contractMetadataURI = contractMetadataURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Must have DEFAULT_ADMIN_ROLE to set base uri");
_baseTokenURI = baseURI;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
if (SniftieUtils.stringContains("://", _tokenURI)) return _tokenURI; // _tokenURI is absolute (e.g. http://domain.com/metadata/1)
return string(abi.encodePacked(base, _tokenURI)); // _tokenURI is an identifier so concatenate with base uri
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, Strings.toString(tokenId)));
}
function setTokenURI(uint256 tokenId, string memory tokenUri) public {
require(_exists(tokenId), "Cannot set metadata hash for nonexistent token");
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Cannot set metadata hash if not admin");
_setTokenURI(tokenId, tokenUri);
}
// this function is needed in children contracts that do not use the standard mint function and
// also do not set the media hash upon minting (a token's media hash must be unique)
function setTokenMediaHash(uint tokenId, string memory mediaHashOrId) public {
require(_exists(tokenId), "Cannot set media hash for nonexistent token");
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Cannot set media hash if not admin");
require(hashes[mediaHashOrId] != 1, "Hash value has already been used");
hashes[mediaHashOrId] = 1;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
| If there is no base URI, return the token URI. | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
}
}
| 2,517,901 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../ValueVaultMaster.sol";
interface IStrategyV2p1 {
function approve(IERC20 _token) external;
function approveForSpender(IERC20 _token, address spender) external;
// Deposit tokens to a farm to yield more tokens.
function deposit(address _vault, uint256 _amount) external; // IStrategy
function deposit(uint256 _poolId, uint256 _amount) external; // IStrategyV2
// Claim farming tokens
function claim(address _vault) external; // IStrategy
function claim(uint256 _poolId) external; // IStrategyV2
// The vault request to harvest the profit
function harvest(uint256 _bankPoolId) external; // IStrategy
function harvest(uint256 _bankPoolId, uint256 _poolId) external; // IStrategyV2
// Withdraw the principal from a farm.
function withdraw(address _vault, uint256 _amount) external; // IStrategy
function withdraw(uint256 _poolId, uint256 _amount) external; // IStrategyV2
// Set 0 to disable quota (no limit)
function poolQuota(uint256 _poolId) external view returns (uint256);
// Use when we want to switch between strategies
function forwardToAnotherStrategy(address _dest, uint256 _amount) external returns (uint256);
function switchBetweenPoolsByGov(uint256 _sourcePoolId, uint256 _destPoolId, uint256 _amount) external; // IStrategyV2p1
// Source LP token of this strategy
function getLpToken() external view returns(address);
// Target farming token of this strategy.
function getTargetToken(address _vault) external view returns(address); // IStrategy
function getTargetToken(uint256 _poolId) external view returns(address); // IStrategyV2
function balanceOf(address _vault) external view returns (uint256); // IStrategy
function balanceOf(uint256 _poolId) external view returns (uint256); // IStrategyV2
function pendingReward(address _vault) external view returns (uint256); // IStrategy
function pendingReward(uint256 _poolId) external view returns (uint256); // IStrategyV2
function expectedAPY(address _vault) external view returns (uint256); // IStrategy
function expectedAPY(uint256 _poolId, uint256 _lpTokenUsdcPrice) external view returns (uint256); // IStrategyV2
function governanceRescueToken(IERC20 _token) external returns (uint256);
}
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
}
interface IValueLiquidPool {
function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint);
function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint);
function calcInGivenOut(uint, uint, uint, uint, uint, uint) external pure returns (uint);
function calcOutGivenIn(uint, uint, uint, uint, uint, uint) external pure returns (uint);
function getDenormalizedWeight(address) external view returns (uint);
function getBalance(address) external view returns (uint);
function swapFee() external view returns (uint);
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewardRate() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external; // Goff, DokiDoki
function stake(uint256 amount, string memory affCode) external; // dego.finance
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
// DokiDoki
function getRewardsAmount(address account) external view returns(uint256);
function claim(uint amount) external;
}
interface ISushiPool {
function deposit(uint256 _poolId, uint256 _amount) external;
function claim(uint256 _poolId) external;
function withdraw(uint256 _poolId, uint256 _amount) external;
function emergencyWithdraw(uint256 _poolId) external;
}
interface IProfitSharer {
function shareProfit() external returns (uint256);
}
interface IValueVaultBank {
function make_profit(uint256 _poolId, uint256 _amount) external;
}
// This contract is owned by Timelock.
// What it does is simple: deposit WETH to pools, and wait for ValueVaultBank's command.
// Atm we support 3 pool types: IStakingRewards (golff.finance), ISushiPool (chickenswap.org), ISodaPool (soda.finance)
contract WETHMultiPoolStrategy is IStrategyV2p1 {
using SafeMath for uint256;
address public strategist;
address public governance;
uint256 public constant FEE_DENOMINATOR = 10000;
IOneSplit public onesplit = IOneSplit(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
ValueVaultMaster public valueVaultMaster;
IERC20 public lpToken; // WETH
mapping(address => mapping(address => address[])) public uniswapPaths; // [input -> output] => uniswap_path
mapping(address => mapping(address => address)) public liquidPools; // [input -> output] => value_liquid_pool (valueliquid.io)
struct PoolInfo {
address vault;
IERC20 targetToken;
address targetPool;
uint256 targetPoolId; // poolId in soda/chicken pool (no use for IStakingRewards pool eg. golff.finance)
uint256 minHarvestForTakeProfit;
uint8 poolType; // 0: IStakingRewards, 1: ISushiPool, 2: ISodaPool, 3: Dego.Finance, 4: DokiDoki.Finance
uint256 poolQuota; // set 0 to disable quota (no limit)
uint256 balance;
}
mapping(uint256 => PoolInfo) public poolMap; // poolIndex -> poolInfo
bool public aggressiveMode; // will try to stake all lpTokens available (be forwarded from bank or from another strategies)
uint8[] public poolPreferredIds; // sorted by preference
// weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
constructor(ValueVaultMaster _valueVaultMaster,
IERC20 _lpToken,
bool _aggressiveMode) public {
valueVaultMaster = _valueVaultMaster;
lpToken = _lpToken;
aggressiveMode = _aggressiveMode;
governance = tx.origin;
strategist = tx.origin;
// Approve all
lpToken.approve(valueVaultMaster.bank(), type(uint256).max);
lpToken.approve(address(unirouter), type(uint256).max);
}
// [0] targetToken: kfcToken = 0xE63684BcF2987892CEfB4caA79BD21b34e98A291
// targetPool: kfcPool = 0x87AE4928f6582376a0489E9f70750334BBC2eb35
// [1] targetToken: degoToken = 0x88EF27e69108B2633F8E1C184CC37940A075cC02
// targetPool: degoPool = 0x28681d373aF03A0Eb00ACE262c5dad9A0C65F276
function setPoolInfo(uint256 _poolId, address _vault, IERC20 _targetToken, address _targetPool, uint256 _targetPoolId, uint256 _minHarvestForTakeProfit, uint8 _poolType, uint256 _poolQuota) external {
require(msg.sender == governance, "!governance");
poolMap[_poolId].vault = _vault;
poolMap[_poolId].targetToken = _targetToken;
poolMap[_poolId].targetPool = _targetPool;
poolMap[_poolId].targetPoolId = _targetPoolId;
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
poolMap[_poolId].poolType = _poolType;
poolMap[_poolId].poolQuota = _poolQuota;
_targetToken.approve(address(unirouter), type(uint256).max);
lpToken.approve(_vault, type(uint256).max);
lpToken.approve(address(_targetPool), type(uint256).max);
}
function approve(IERC20 _token) external override {
require(msg.sender == governance, "!governance");
_token.approve(valueVaultMaster.bank(), type(uint256).max);
_token.approve(address(unirouter), type(uint256).max);
}
function approveForSpender(IERC20 _token, address spender) external override {
require(msg.sender == governance, "!governance");
_token.approve(spender, type(uint256).max);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
strategist = _strategist;
}
function setPoolPreferredIds(uint8[] memory _poolPreferredIds) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
delete poolPreferredIds;
for (uint8 i = 0; i < _poolPreferredIds.length; ++i) {
poolPreferredIds.push(_poolPreferredIds[i]);
}
}
function setMinHarvestForTakeProfit(uint256 _poolId, uint256 _minHarvestForTakeProfit) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
}
function setPoolQuota(uint256 _poolId, uint256 _poolQuota) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].poolQuota = _poolQuota;
}
// Sometime the balance could be slightly changed (due to the pool, or because we call xxxByGov methods)
function setPoolBalance(uint256 _poolId, uint256 _balance) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].balance = _balance;
}
function setTotalBalance(uint256 _totalBalance) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
totalBalance = _totalBalance;
}
function setAggressiveMode(bool _aggressiveMode) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
aggressiveMode = _aggressiveMode;
}
function setOnesplit(IOneSplit _onesplit) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
onesplit = _onesplit;
}
function setUnirouter(IUniswapRouter _unirouter) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
unirouter = _unirouter;
}
/**
* @dev See {IStrategy-deposit}.
*/
function deposit(address _vault, uint256 _amount) public override {
require(valueVaultMaster.isVault(msg.sender), "sender not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
uint256 _quota = poolMap[_pid].poolQuota;
if (_quota == 0 || balanceOf(_pid) < _quota) {
_deposit(_pid, _amount);
return;
}
}
}
revert("Exceeded pool quota");
}
/**
* @dev See {IStrategyV2-deposit}.
*/
function deposit(uint256 _poolId, uint256 _amount) public override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
_deposit(_poolId, _amount);
}
function _deposit(uint256 _poolId, uint256 _amount) internal {
PoolInfo storage pool = poolMap[_poolId];
if (aggressiveMode) {
_amount = lpToken.balanceOf(address(this));
}
if (pool.poolType == 0 || pool.poolType == 4) {
IStakingRewards(pool.targetPool).stake(_amount);
} else if (pool.poolType == 3) {
IStakingRewards(pool.targetPool).stake(_amount, string("valuedefidev02"));
} else {
ISushiPool(pool.targetPool).deposit(pool.targetPoolId, _amount);
}
pool.balance = pool.balance.add(_amount);
totalBalance = totalBalance.add(_amount);
}
/**
* @dev See {IStrategy-claim}.
*/
function claim(address _vault) external override {
require(valueVaultMaster.isVault(_vault), "not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_claim(_pid);
}
}
}
/**
* @dev See {IStrategyV2-claim}.
*/
function claim(uint256 _poolId) external override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
_claim(_poolId);
}
function _claim(uint256 _poolId) internal {
PoolInfo storage pool = poolMap[_poolId];
if (pool.poolType == 0 || pool.poolType == 3) {
IStakingRewards(pool.targetPool).getReward();
} else if (pool.poolType == 4) {
IStakingRewards(pool.targetPool).claim(IStakingRewards(pool.targetPool).getRewardsAmount(address(this)));
} else if (pool.poolType == 1) {
ISushiPool(pool.targetPool).deposit(pool.targetPoolId, 0);
} else {
ISushiPool(pool.targetPool).claim(pool.targetPoolId);
}
}
/**
* @dev See {IStrategy-withdraw}.
*/
function withdraw(address _vault, uint256 _amount) external override {
require(valueVaultMaster.isVault(msg.sender), "sender not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = poolPreferredIds.length; i >= 1; --i) {
uint256 _pid = poolPreferredIds[i - 1];
if (poolMap[_pid].vault == _vault) {
uint256 _bal = poolMap[_pid].balance;
if (_bal > 0) {
_withdraw(_pid, (_bal > _amount) ? _amount : _bal);
uint256 strategyBal = lpToken.balanceOf(address(this));
lpToken.transfer(valueVaultMaster.bank(), strategyBal);
if (strategyBal >= _amount) break;
if (strategyBal > 0) _amount = _amount - strategyBal;
}
}
}
}
/**
* @dev See {IStrategyV2-withdraw}.
*/
function withdraw(uint256 _poolId, uint256 _amount) external override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
if (lpToken.balanceOf(address(this)) >= _amount) return; // has enough balance, no need to withdraw from pool
_withdraw(_poolId, _amount);
}
function _withdraw(uint256 _poolId, uint256 _amount) internal {
PoolInfo storage pool = poolMap[_poolId];
if (pool.poolType == 0 || pool.poolType == 3 || pool.poolType == 4) {
IStakingRewards(pool.targetPool).withdraw(_amount);
} else {
ISushiPool(pool.targetPool).withdraw(pool.targetPoolId, _amount);
}
if (pool.balance < _amount) {
_amount = pool.balance;
}
pool.balance = pool.balance - _amount;
if (totalBalance >= _amount) totalBalance = totalBalance - _amount;
}
function depositByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0 || _poolType == 4) {
IStakingRewards(pool).stake(_amount);
} else if (_poolType == 3) {
IStakingRewards(pool).stake(_amount, string("valuedefidev02"));
} else {
ISushiPool(pool).deposit(_targetPoolId, _amount);
}
}
function claimByGov(address pool, uint8 _poolType, uint256 _targetPoolId) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0 || _poolType == 3) {
IStakingRewards(pool).getReward();
} else if (_poolType == 4) {
IStakingRewards(pool).claim(IStakingRewards(pool).getRewardsAmount(address(this)));
} else if (_poolType == 1) {
ISushiPool(pool).deposit(_targetPoolId, 0);
} else {
ISushiPool(pool).claim(_targetPoolId);
}
}
function withdrawByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0 || _poolType == 3 || _poolType == 4) {
IStakingRewards(pool).withdraw(_amount);
} else {
ISushiPool(pool).withdraw(_targetPoolId, _amount);
}
}
function emergencyWithdrawByGov(address pool, uint256 _targetPoolId) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
ISushiPool(pool).emergencyWithdraw(_targetPoolId);
}
function switchBetweenPoolsByGov(uint256 _sourcePoolId, uint256 _destPoolId, uint256 _amount) external override {
require(msg.sender == governance, "!governance");
_withdraw(_sourcePoolId, _amount);
_deposit(_destPoolId, _amount);
}
/**
* @dev See {IStrategyV2-poolQuota}
*/
function poolQuota(uint256 _poolId) external override view returns (uint256) {
return poolMap[_poolId].poolQuota;
}
/**
* @dev See {IStrategyV2-forwardToAnotherStrategy}
*/
function forwardToAnotherStrategy(address _dest, uint256 _amount) external override returns (uint256 sent) {
require(valueVaultMaster.isVault(msg.sender), "not vault");
require(valueVaultMaster.isStrategy(_dest), "not strategy");
require(IStrategyV2p1(_dest).getLpToken() == address(lpToken), "!lpToken");
uint256 lpTokenBal = lpToken.balanceOf(address(this));
sent = (_amount < lpTokenBal) ? _amount : lpTokenBal;
lpToken.transfer(_dest, sent);
}
function setUnirouterPath(address _input, address _output, address [] memory _path) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
uniswapPaths[_input][_output] = _path;
}
function setLiquidPool(address _input, address _output, address _pool) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
liquidPools[_input][_output] = _pool;
IERC20(_input).approve(_pool, type(uint256).max);
}
function _swapTokens(address _input, address _output, uint256 _amount) internal {
address _pool = liquidPools[_input][_output];
if (_pool != address(0)) { // use ValueLiquid
// swapExactAmountIn(tokenIn, tokenAmountIn, tokenOut, minAmountOut, maxPrice)
IValueLiquidPool(_pool).swapExactAmountIn(_input, _amount, _output, 1, type(uint256).max);
} else { // use Uniswap
address[] memory path = uniswapPaths[_input][_output];
if (path.length == 0) {
// path: _input -> _output
path = new address[](2);
path[0] = _input;
path[1] = _output;
}
// swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline)
unirouter.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(1800));
}
}
/**
* @dev See {IStrategy-harvest}.
*/
function harvest(uint256 _bankPoolId) external override {
address _vault = msg.sender;
require(valueVaultMaster.isVault(_vault), "!vault"); // additional protection so we don't burn the funds
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_harvest(_bankPoolId, _pid);
}
}
}
/**
* @dev See {IStrategy-harvest}.
*/
function harvest(uint256 _bankPoolId, uint256 _poolId) external override {
require(valueVaultMaster.isVault(msg.sender), "!vault"); // additional protection so we don't burn the funds
_harvest(_bankPoolId, _poolId);
}
function _harvest(uint256 _bankPoolId, uint256 _poolId) internal {
PoolInfo storage pool = poolMap[_poolId];
_claim(_poolId);
IERC20 targetToken = pool.targetToken;
uint256 targetTokenBal = targetToken.balanceOf(address(this));
if (targetTokenBal < pool.minHarvestForTakeProfit) return;
_swapTokens(address(targetToken), address(lpToken), targetTokenBal);
uint256 wethBal = lpToken.balanceOf(address(this));
if (wethBal > 0) {
address profitSharer = valueVaultMaster.profitSharer();
address performanceReward = valueVaultMaster.performanceReward();
address bank = valueVaultMaster.bank();
if (valueVaultMaster.govVaultProfitShareFee() > 0 && profitSharer != address(0)) {
address _govToken = valueVaultMaster.yfv();
uint256 _govVaultProfitShareFee = wethBal.mul(valueVaultMaster.govVaultProfitShareFee()).div(FEE_DENOMINATOR);
_swapTokens(address(lpToken), _govToken, _govVaultProfitShareFee);
IERC20(_govToken).transfer(profitSharer, IERC20(_govToken).balanceOf(address(this)));
IProfitSharer(profitSharer).shareProfit();
}
if (valueVaultMaster.gasFee() > 0 && performanceReward != address(0)) {
uint256 _gasFee = wethBal.mul(valueVaultMaster.gasFee()).div(FEE_DENOMINATOR);
lpToken.transfer(performanceReward, _gasFee);
}
uint256 balanceLeft = lpToken.balanceOf(address(this));
if (lpToken.allowance(address(this), bank) < balanceLeft) {
lpToken.approve(bank, 0);
lpToken.approve(bank, balanceLeft);
}
IValueVaultBank(bank).make_profit(_bankPoolId, balanceLeft);
}
}
/**
* @dev See {IStrategyV2-getLpToken}.
*/
function getLpToken() external view override returns(address) {
return address(lpToken);
}
/**
* @dev See {IStrategy-getTargetToken}.
* Always use pool 0 (default).
*/
function getTargetToken(address) external override view returns(address) {
return address(poolMap[0].targetToken);
}
/**
* @dev See {IStrategyV2-getTargetToken}.
*/
function getTargetToken(uint256 _poolId) external override view returns(address) {
return address(poolMap[_poolId].targetToken);
}
function balanceOf(address _vault) public override view returns (uint256 _balanceOfVault) {
_balanceOfVault = 0;
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_balanceOfVault = _balanceOfVault.add(poolMap[_pid].balance);
}
}
}
function balanceOf(uint256 _poolId) public override view returns (uint256) {
return poolMap[_poolId].balance;
}
function pendingReward(address) public override view returns (uint256) {
return pendingReward(0);
}
// Only support IStakingRewards pool
function pendingReward(uint256 _poolId) public override view returns (uint256) {
if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types
return IStakingRewards(poolMap[_poolId].targetPool).earned(address(this));
}
// always use pool 0 (default)
function expectedAPY(address) public override view returns (uint256) {
return expectedAPY(0, 0);
}
// Helper function - should never use it on-chain.
// Only support IStakingRewards pool.
// Return 10000x of APY. _lpTokenUsdcPrice is not used.
function expectedAPY(uint256 _poolId, uint256) public override view returns (uint256) {
if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types
IStakingRewards targetPool = IStakingRewards(poolMap[_poolId].targetPool);
uint256 totalSupply = targetPool.totalSupply();
if (totalSupply == 0) return 0;
uint256 investAmt = poolMap[_poolId].balance;
uint256 oneHourReward = targetPool.rewardRate().mul(3600);
uint256 returnAmt = oneHourReward.mul(investAmt).div(totalSupply);
IERC20 usdc = IERC20(valueVaultMaster.usdc());
(uint256 investInUSDC, ) = onesplit.getExpectedReturn(lpToken, usdc, investAmt, 10, 0);
(uint256 returnInUSDC, ) = onesplit.getExpectedReturn(poolMap[_poolId].targetToken, usdc, returnAmt, 10, 0);
return returnInUSDC.mul(8760).mul(FEE_DENOMINATOR).div(investInUSDC); // 100 -> 1%
}
event ExecuteTransaction(address indexed target, uint value, string signature, bytes data);
/**
* @dev This is from Timelock contract, the governance should be a Timelock contract before calling this
*/
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public returns (bytes memory) {
require(msg.sender == governance, "!governance");
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "WETHMultiPoolStrategy::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
/**
* @dev if there is any token stuck we will need governance support to rescue the fund
*/
function governanceRescueToken(IERC20 _token) external override returns (uint256 balance) {
address bank = valueVaultMaster.bank();
require(bank == msg.sender, "sender not bank");
balance = _token.balanceOf(address(this));
_token.transfer(bank, balance);
}
}
| See {IStrategyV2-getLpToken}./ | function getLpToken() external view override returns(address) {
return address(lpToken);
}
| 6,359,578 |
./partial_match/1/0x4d2265D0DADB5DDf6e114bd586279F899E9E767e/sources/PEPENATOR.sol | 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 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);
}
| 9,411,623 |
//Address: 0x9EA80e204045329Ba752D03C395F82A12799f13d
//Contract name: BlocklancerToken
//Balance: 25.666372541 Ether
//Verification Date: 8/6/2017
//Transacion Count: 222
// CODE STARTS HERE
//--------------------------------------------------------------//
//---------------------BLOCKLANCER TOKEN -----------------------//
//--------------------------------------------------------------//
pragma solidity ^0.4.8;
/// Migration Agent
/// allows us to migrate to a new contract should it be needed
/// makes blocklancer future proof
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract ERC20Interface {
// Get the total token supply
function totalSupply() constant returns (uint256 totalSupply);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address _spender, uint256 _value) returns (bool success);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/// Blocklancer Token (LNC) - crowdfunding code for Blocklancer Project
contract BlocklancerToken is ERC20Interface {
string public constant name = "Lancer Token";
string public constant symbol = "LNC";
uint8 public constant decimals = 18; // 18 decimal places, the same as ETH.
// The funding cap in weis.
uint256 public constant tokenCreationCap = 1000000000* 10**18;
uint256 public constant tokenCreationMin = 150000000* 10**18;
mapping(address => mapping (address => uint256)) allowed;
uint public fundingStart;
uint public fundingEnd;
// The flag indicates if the LNC contract is in Funding state.
bool public funding = true;
// Receives ETH and its own LNC endowment.
address public master;
// The current total token supply.
uint256 totalTokens;
//needed to calculate the price after the power day
//the price increases by 1 % for every 10 million LNC sold after power day
uint256 soldAfterPowerHour;
mapping (address => uint256) balances;
mapping (address => uint) lastTransferred;
//needed to refund everyone should the ICO fail
// needed because the price per LNC isn't linear
mapping (address => uint256) balancesEther;
//address of the contract that manages the migration
//can only be changed by the creator
address public migrationAgent;
//total amount of token migrated
//allows everyone to see the progress of the migration
uint256 public totalMigrated;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);
//total amount of participants in the ICO
uint totalParticipants;
function BlocklancerToken() {
master = msg.sender;
fundingStart = 1501977600;
//change first number!
fundingEnd = fundingStart + 31 * 1 days;//now + 1000 * 1 minutes;
}
//returns the total amount of participants in the ICO
function getAmountofTotalParticipants() constant returns (uint){
return totalParticipants;
}
//set
function getAmountSoldAfterPowerDay() constant external returns(uint256){
return soldAfterPowerHour;
}
/// allows to transfer token to another address
function transfer(address _to, uint256 _value) returns (bool success) {
// Don't allow in funding state
if(funding) throw;
var senderBalance = balances[msg.sender];
//only allow if the balance of the sender is more than he want's to send
if (senderBalance >= _value && _value > 0) {
//reduce the sender balance by the amount he sends
senderBalance -= _value;
balances[msg.sender] = senderBalance;
//increase the balance of the receiver by the amount we reduced the balance of the sender
balances[_to] += _value;
//saves the last time someone sent LNc from this address
//is needed for our Token Holder Tribunal
//this ensures that everyone can only vote one time
//otherwise it would be possible to send the LNC around and everyone votes again and again
lastTransferred[msg.sender]=block.timestamp;
Transfer(msg.sender, _to, _value);
return true;
}
//transfer failed
return false;
}
//returns the total amount of LNC in circulation
//get displayed on the website whilst the crowd funding
function totalSupply() constant returns (uint256 totalSupply) {
return totalTokens;
}
//retruns the balance of the owner address
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
//returns the amount anyone pledged into this contract
function EtherBalanceOf(address _owner) constant returns (uint256) {
return balancesEther[_owner];
}
//time left before the crodsale ends
function TimeLeft() external constant returns (uint256) {
if(fundingEnd>block.timestamp)
return fundingEnd-block.timestamp;
else
return 0;
}
//time left before the crodsale begins
function TimeLeftBeforeCrowdsale() external constant returns (uint256) {
if(fundingStart>block.timestamp)
return fundingStart-block.timestamp;
else
return 0;
}
// allows us to migrate to anew contract
function migrate(uint256 _value) external {
// can only be called if the funding ended
if(funding) throw;
//the migration agent address needs to be set
if(migrationAgent == 0) throw;
// must migrate more than nothing
if(_value == 0) throw;
//if the value is higher than the sender owns abort
if(_value > balances[msg.sender]) throw;
//reduce the balance of the owner
balances[msg.sender] -= _value;
//reduce the token left in the old contract
totalTokens -= _value;
totalMigrated += _value;
//call the migration agent to complete the migration
//credits the same amount of LNC in the new contract
MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value);
Migrate(msg.sender, migrationAgent, _value);
}
//sets the address of the migration agent
function setMigrationAgent(address _agent) external {
//not possible in funding mode
if(funding) throw;
//only allow to set this once
if(migrationAgent != 0) throw;
//anly the owner can call this function
if(msg.sender != master) throw;
//set the migration agent
migrationAgent = _agent;
}
//return the current exchange rate -> LNC per Ether
function getExchangeRate() constant returns(uint){
//15000 LNC at power day
if(fundingStart + 1 * 1 days > block.timestamp){
return 15000;
}
//otherwise reduce by 1 % every 10 million LNC sold
else{
uint256 decrease=100-(soldAfterPowerHour/10000000/1000000000000000000);
if(decrease<70){
decrease=70;
}
return 10000*decrease/100;
}
}
//returns if the crowd sale is still open
function ICOopen() constant returns(bool){
if(!funding) return false;
else if(block.timestamp < fundingStart) return false;
else if(block.timestamp > fundingEnd) return false;
else if(tokenCreationCap <= totalTokens) return false;
else return true;
}
// Crowdfunding:
//when someone send ether to this contract
function() payable external {
//not possible if the funding has ended
if(!funding) throw;
//not possible before the funding started
if(block.timestamp < fundingStart) throw;
//not possible after the funding ended
if(block.timestamp > fundingEnd) throw;
// Do not allow creating 0 or more than the cap tokens.
if(msg.value == 0) throw;
//don't allow to create more token than the maximum cap
if((msg.value * getExchangeRate()) > (tokenCreationCap - totalTokens)) throw;
//calculate the amount of LNC the sender receives
var numTokens = msg.value * getExchangeRate();
totalTokens += numTokens;
//increase the amount of token sold after power day
//allows us to calculate the 1 % price increase per 10 million LNC sold
if(getExchangeRate()!=15000){
soldAfterPowerHour += numTokens;
}
// increase the amount of token the sender holds
balances[msg.sender] += numTokens;
//increase the amount of ether the sender pledged into the contract
balancesEther[msg.sender] += msg.value;
//icrease the amount of people that sent ether to this contract
totalParticipants+=1;
// Log token creation
Transfer(0, msg.sender, numTokens);
}
//called after the crodsale ended
//needed to allow everyone to send their LNC around
function finalize() external {
// not possible if the funding already ended
if(!funding) throw;
//only possible if funding ended and the minimum cap is reached - or
//the total amount of token is the same as the maximum cap
if((block.timestamp <= fundingEnd ||
totalTokens < tokenCreationMin) &&
(totalTokens+5000000000000000000000) < tokenCreationCap) throw;
// allows to tranfer token to another address
// disables buying LNC
funding = false;
//send 12% of the token to the devs
//10 % for the devs
//2 % for the bounty participants
uint256 percentOfTotal = 12;
uint256 additionalTokens = totalTokens * percentOfTotal / (100 - percentOfTotal);
totalTokens += additionalTokens;
balances[master] += additionalTokens;
Transfer(0, master, additionalTokens);
// Transfer ETH to the Blocklancer address.
if (!master.send(this.balance)) throw;
}
//everyone needs to call this function should the minimum cap not be reached
//refunds the sender
function refund() external {
// not possible after the ICO was finished
if(!funding) throw;
//not possible before the ICO ended
if(block.timestamp <= fundingEnd) throw;
//not possible if more token were created than the minimum
if(totalTokens >= tokenCreationMin) throw;
var lncValue = balances[msg.sender];
var ethValue = balancesEther[msg.sender];
if (lncValue == 0) throw;
//set the amount of token the sender has to 0
balances[msg.sender] = 0;
//set the amount of ether the sender owns to 0
balancesEther[msg.sender] = 0;
totalTokens -= lncValue;
Refund(msg.sender, ethValue);
if (!msg.sender.send(ethValue)) throw;
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from,address _to,uint256 _amount) returns (bool success) {
if(funding) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
if(funding) throw;
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
| return the current exchange rate -> LNC per Ether15000 LNC at power dayotherwise reduce by 1 % every 10 million LNC sold | function getExchangeRate() constant returns(uint){
if(fundingStart + 1 * 1 days > block.timestamp){
return 15000;
}
else{
uint256 decrease=100-(soldAfterPowerHour/10000000/1000000000000000000);
if(decrease<70){
decrease=70;
}
return 10000*decrease/100;
}
}
| 1,085,775 |
./full_match/11155111/0x740cEad2acda5C7BE0152bAcEDDB059cA4786feC/sources/project:/contracts/Vault.sol | allow any token holder to swap their tokens for the underlying assets amount the amount of tokens to swap (in the smallest unit of the token)/ Burn the tokens get the fee Transfer the underlying assets | function redeem(uint256 amount) external {
require (balanceOf(msg.sender) >= amount, "Not enough tokens to burn");
_burn(msg.sender, amount);
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20 underlyingToken = IERC20(_tokens[i].tokenAddress);
uint256 fee = amount / _mintAndBurnFee;
uint256 underlyingAmount = (amount - fee) * _tokens[i].allocation;
underlyingToken.transfer(msg.sender, underlyingAmount - fee);
}
emit RedeemAndBurn(msg.sender, amount);
}
| 3,804,718 |
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.5.12;
contract DSPauseAbstract {
function SETOWNER297(address) external; //inject NONSTANDARD NAMING
function SETAUTHORITY462(address) external; //inject NONSTANDARD NAMING
function SETDELAY997(uint256) external; //inject NONSTANDARD NAMING
function PLANS194(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function PROXY33() external view returns (address); //inject NONSTANDARD NAMING
function DELAY572() external view returns (uint256); //inject NONSTANDARD NAMING
function PLOT308(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function DROP835(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function EXEC528(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING
}
contract JugAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function VOW865() external view returns (address); //inject NONSTANDARD NAMING
function BASE98() external view returns (address); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function DRIP851(bytes32) external returns (uint256); //inject NONSTANDARD NAMING
}
contract VatAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function CAN701(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function HOPE401(address) external; //inject NONSTANDARD NAMING
function NOPE804(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING
function URNS72(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DAI766(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBT96() external view returns (uint256); //inject NONSTANDARD NAMING
function VICE796() external view returns (uint256); //inject NONSTANDARD NAMING
function LINE365() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
function SLIP893(bytes32, address, int256) external; //inject NONSTANDARD NAMING
function FLUX455(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function MOVE486(address, address, uint256) external; //inject NONSTANDARD NAMING
function FROB749(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function FORK68(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function GRAB867(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function SUCK979(address, address, uint256) external; //inject NONSTANDARD NAMING
function FOLD739(bytes32, address, int256) external; //inject NONSTANDARD NAMING
}
contract VowAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address usr) external; //inject NONSTANDARD NAMING
function DENY29(address usr) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function FLAPPER608() external view returns (address); //inject NONSTANDARD NAMING
function FLOPPER190() external view returns (address); //inject NONSTANDARD NAMING
function SIN979(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979() external view returns (uint256); //inject NONSTANDARD NAMING
function ASH807() external view returns (uint256); //inject NONSTANDARD NAMING
function WAIT426() external view returns (uint256); //inject NONSTANDARD NAMING
function DUMP329() external view returns (uint256); //inject NONSTANDARD NAMING
function SUMP140() external view returns (uint256); //inject NONSTANDARD NAMING
function BUMP430() external view returns (uint256); //inject NONSTANDARD NAMING
function HUMP834() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function FESS945(uint256) external; //inject NONSTANDARD NAMING
function FLOG837(uint256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function KISS865(uint256) external; //inject NONSTANDARD NAMING
function FLOP497() external returns (uint256); //inject NONSTANDARD NAMING
function FLAP923() external returns (uint256); //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
}
contract IlkRegistryAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function CAT738() external view returns (address); //inject NONSTANDARD NAMING
function SPOT274() external view returns (address); //inject NONSTANDARD NAMING
function ILKDATA365(bytes32) external view returns ( //inject NONSTANDARD NAMING
uint256,
address,
address,
address,
address,
uint256,
string memory,
string memory
);
function ILKS89() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function ILKS89(uint) external view returns (bytes32); //inject NONSTANDARD NAMING
function ADD269(address) external; //inject NONSTANDARD NAMING
function REMOVE614(bytes32) external; //inject NONSTANDARD NAMING
function REMOVEAUTH234(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, string calldata) external; //inject NONSTANDARD NAMING
function COUNT649() external view returns (uint256); //inject NONSTANDARD NAMING
function LIST141() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function LIST141(uint256, uint256) external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function GET51(uint256) external view returns (bytes32); //inject NONSTANDARD NAMING
function INFO652(bytes32) external view returns ( //inject NONSTANDARD NAMING
string memory,
string memory,
uint256,
address,
address,
address,
address
);
function POS804(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function PIP889(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function JOIN697(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function FLIP981(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function DEC837(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function SYMBOL988(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
function NAME950(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/c8e9f709f4bc5d0384b47e0109eb7555f08b84fc/governance/votes/Executive%20vote%20-%20August%2014%2C%202020.md -q -O - 2>/dev/null)"
string constant public description524 = //inject NONSTANDARD NAMING
"2020-08-14 MakerDAO Weekly Executive Spell | Hash: 0x97294bc0de2100192a54a618351a84574e5d1998da234152e68b4065ac9bea0f";
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 6%):
//
// $ bc -l <<< 'scale=27; e( l(1.06)/(60 * 60 * 24 * 365) )'
//
uint256 constant six_pct_rate891 = 1000000001847694957439350562; //inject NONSTANDARD NAMING
uint256 constant fortyfour_pct_rate631 = 1000000011562757347033522598; //inject NONSTANDARD NAMING
function EXECUTE336() external { //inject NONSTANDARD NAMING
bytes32[] memory ilks = IlkRegistryAbstract(ilk_registry964).LIST141();
for(uint i = 0; i < ilks.length; i++) {
// Set all ilks dust value from 20 Dai to 100 Dai
VatAbstract(mcd_vat35).FILE935(ilks[i], "dust", 100 * rad54);
}
// Set the MANA-A stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 8%
// New Rate: 6%
JugAbstract(mcd_jug497).DRIP851("MANA-A");
JugAbstract(mcd_jug497).FILE935("MANA-A", "duty", six_pct_rate891);
// Set the USDC-B stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 46%
// New Rate: 44%
JugAbstract(mcd_jug497).DRIP851("USDC-B");
JugAbstract(mcd_jug497).FILE935("USDC-B", "duty", fortyfour_pct_rate631);
// Sets the system surplus buffer from 500k Dai to 2mm Dai
VowAbstract(mcd_vow892).FILE935("hump", 2 * million677 * rad54);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
function DESCRIPTION887() public view returns (string memory) { //inject NONSTANDARD NAMING
return SpellAction(action).description524();
}
function SCHEDULE900() public { //inject NONSTANDARD NAMING
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).DELAY572();
pause.PLOT308(action, tag, sig, eta);
}
function CAST355() public { //inject NONSTANDARD NAMING
require(!done, "spell-already-cast");
done = true;
pause.EXEC528(action, tag, sig, eta);
}
} | inject NONSTANDARD NAMING | function FILE935(bytes32, bytes32, uint256) external; | 12,918,539 |
// SPDX-License-Identifier: GPL-3.0-or-later
/** ____________________________________________________________________________________
___________/\/\/\/\________/\/\____/\/\______/\/\/\/\/\________/\/\/\/\/\/\_________
_________/\/\____/\/\______/\/\____/\/\______/\/\____/\/\____________/\/\___________
_________/\/\____/\/\______/\/\____/\/\______/\/\/\/\/\____________/\/\_____________
_________/\/\____/\/\______/\/\____/\/\______/\/\__/\/\__________/\/\_______________
___________/\/\/\/\__________/\/\/\/\________/\/\____/\/\______/\/\/\/\/\/\_________
____________________________________________________________________________________ */
pragma solidity 0.8.4;
import {OurSplitter} from "./OurSplitter.sol";
import {OurMinter} from "./OurMinter.sol";
import {OurIntrospector} from "./OurIntrospector.sol";
/**
* @title OurPylon
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurPylon is OurSplitter, OurMinter, OurIntrospector {
// Disables modification of Pylon after deployment
constructor() {
threshold = 1;
}
/**
* @dev Setup function sets initial storage of Poxy.
* @param owners_ List of addresses that can execute transactions other than claiming funds.
* @notice see OurManagement -> setupOwners()
* @notice approves Zora AH to handle Zora ERC721s
*/
function setup(address[] calldata owners_) external {
setupOwners(owners_);
emit SplitSetup(owners_);
// Approve Zora AH
_setApprovalForAH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {OurStorage} from "./OurStorage.sol";
interface IERC20 {
function transfer(address recipient, uint256 amount)
external
returns (bool);
function balanceOf(address account) external view returns (uint256);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title OurSplitter
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurSplitter is OurStorage {
struct Proof {
bytes32[] merkleProof;
}
uint256 public constant PERCENTAGE_SCALE = 10e5;
/**======== Subgraph =========
* ETHReceived - emits sender and value in receive() fallback
* WindowIncremented - emits current claim window, and available value of ETH
* TransferETH - emits to address, value, and success bool
* TransferERC20 - emits token's contract address and total transferred amount
*/
event ETHReceived(address indexed sender, uint256 value);
event WindowIncremented(uint256 currentWindow, uint256 fundsAvailable);
event TransferETH(address account, uint256 amount, bool success);
event TransferERC20(address token, uint256 amount);
// Plain ETH transfers
receive() external payable {
_depositedInWindow += msg.value;
emit ETHReceived(msg.sender, msg.value);
}
function claimETH(
uint256 window,
address account,
uint256 scaledPercentageAllocation,
bytes32[] calldata merkleProof
) external {
require(currentWindow > window, "cannot claim for a future window");
require(
!isClaimed(window, account),
"Account already claimed the given window"
);
_setClaimed(window, account);
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, scaledPercentageAllocation)
),
"Invalid proof"
);
_transferETHOrWETH(
account,
// The absolute amount that's claimable.
scaleAmountByPercentage(
balanceForWindow[window],
scaledPercentageAllocation
)
);
}
/**
* @dev Attempts transferring entire balance of an ERC20 to corresponding Recipients
* @notice if amount of tokens are not equally divisible according to allocation
* the remainder will be forwarded to accounts[0].
* In most cases, the difference will be negligible:
* ~remainder × 10^-17,
* or about 0.000000000000000100 at most.
* @notice iterating through an array to push payments goes against best practices,
* therefore it is advised to avoid accepting ERC-20s as payment.
*/
function claimERC20ForAll(
address tokenAddress,
address[] calldata accounts,
uint256[] calldata allocations,
Proof[] calldata merkleProofs
) external {
require(
_verifyProof(
merkleProofs[0].merkleProof,
merkleRoot,
_getNode(accounts[0], allocations[0])
),
"Invalid proof for Account 0"
);
uint256 erc20Balance = IERC20(tokenAddress).balanceOf(address(this));
for (uint256 i = 1; i < accounts.length; i++) {
require(
_verifyProof(
merkleProofs[i].merkleProof,
merkleRoot,
_getNode(accounts[i], allocations[i])
),
"Invalid proof"
);
uint256 scaledAmount = scaleAmountByPercentage(
erc20Balance,
allocations[i]
);
_attemptERC20Transfer(tokenAddress, accounts[i], scaledAmount);
}
_attemptERC20Transfer(
tokenAddress,
accounts[0],
IERC20(tokenAddress).balanceOf(address(this))
);
emit TransferERC20(tokenAddress, erc20Balance);
}
function claimETHForAllWindows(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) external {
// Make sure that the user has this allocation granted.
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, percentageAllocation)
),
"Invalid proof"
);
uint256 amount = 0;
for (uint256 i = 0; i < currentWindow; i++) {
if (!isClaimed(i, account)) {
_setClaimed(i, account);
amount += scaleAmountByPercentage(
balanceForWindow[i],
percentageAllocation
);
}
}
_transferETHOrWETH(account, amount);
}
function incrementThenClaimAll(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) external {
incrementWindow();
_claimAll(account, percentageAllocation, merkleProof);
}
function incrementWindow() public {
uint256 fundsAvailable;
if (currentWindow == 0) {
fundsAvailable = address(this).balance;
} else {
// Current Balance, subtract previous balance to get the
// funds that were added for this window.
fundsAvailable = _depositedInWindow;
}
_depositedInWindow = 0;
require(fundsAvailable > 0, "No additional funds for window");
balanceForWindow.push(fundsAvailable);
currentWindow += 1;
emit WindowIncremented(currentWindow, fundsAvailable);
}
function isClaimed(uint256 window, address account)
public
view
returns (bool)
{
return _claimed[_getClaimHash(window, account)];
}
function scaleAmountByPercentage(uint256 amount, uint256 scaledPercent)
public
pure
returns (uint256 scaledAmount)
{
/* Example:
BalanceForWindow = 100 ETH // Allocation = 2%
To find out the amount we use, for example: (100 * 200) / (100 * 100)
which returns 2 -- i.e. 2% of the 100 ETH balance.
*/
scaledAmount = (amount * scaledPercent) / (100 * PERCENTAGE_SCALE);
}
/// @notice same as claimETHForAllWindows() but marked private for use in incrementThenClaimAll()
function _claimAll(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) private {
// Make sure that the user has this allocation granted.
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, percentageAllocation)
),
"Invalid proof"
);
uint256 amount = 0;
for (uint256 i = 0; i < currentWindow; i++) {
if (!isClaimed(i, account)) {
_setClaimed(i, account);
amount += scaleAmountByPercentage(
balanceForWindow[i],
percentageAllocation
);
}
}
_transferETHOrWETH(account, amount);
}
//======== Private Functions ========
function _setClaimed(uint256 window, address account) private {
_claimed[_getClaimHash(window, account)] = true;
}
// Will attempt to transfer ETH, but will transfer WETH instead if it fails.
function _transferETHOrWETH(address to, uint256 value)
private
returns (bool didSucceed)
{
// Try to transfer ETH to the given recipient.
didSucceed = _attemptETHTransfer(to, value);
if (!didSucceed) {
// If the transfer fails, wrap and send as WETH, so that
// the auction is not impeded and the recipient still
// can claim ETH via the WETH contract (similar to escrow).
IWETH(WETH).deposit{value: value}();
IWETH(WETH).transfer(to, value);
// At this point, the recipient can unwrap WETH.
didSucceed = true;
}
emit TransferETH(to, value, didSucceed);
}
function _attemptETHTransfer(address to, uint256 value)
private
returns (bool)
{
// Here increase the gas limit a reasonable amount above the default, and try
// to send ETH to the recipient.
// NOTE: This might allow the recipient to attempt a limited reentrancy attack.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = to.call{value: value, gas: 30000}("");
return success;
}
/**
* @dev Transfers ERC20s
* @notice Reverts entire transaction if one fails
* @notice A rogue owner could easily bypass countermeasures. Provided as last resort,
* in case Proxy receives ERC20.
*/
function _attemptERC20Transfer(
address tokenAddress,
address splitRecipient,
uint256 allocatedAmount
) private {
bool didSucceed = IERC20(tokenAddress).transfer(
splitRecipient,
allocatedAmount
);
require(didSucceed);
}
function _getClaimHash(uint256 window, address account)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(window, account));
}
function _amountFromPercent(uint256 amount, uint32 percent)
private
pure
returns (uint256)
{
// Solidity 0.8.0 lets us do this without SafeMath.
return (amount * percent) / 100;
}
function _getNode(address account, uint256 percentageAllocation)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account, percentageAllocation));
}
// From https://github.com/protofire/zeppelin-solidity/blob/master/contracts/MerkleProof.sol
function _verifyProof(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) private pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
pragma experimental ABIEncoderV2;
import {OurManagement} from "./OurManagement.sol";
import {IZora} from "./interfaces/IZora.sol";
import {IERC721} from "./interfaces/IERC721.sol";
/**
* @title OurMinter
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*
*
*
* @notice Some functions are marked as 'untrusted'Function. Use caution when interacting
* with these, as any contracts you supply could be potentially unsafe.
* 'Trusted' functions on the other hand -- implied by the absence of 'untrusted' --
* are hardcoded to use the Zora Protocol addresses.
* https://consensys.github.io/smart-contract-best-practices/recommendations/#mark-untrusted-contracts
*/
contract OurMinter is OurManagement {
address public constant ZORA_MEDIA =
0xabEFBc9fD2F806065b4f3C237d4b59D9A97Bcac7;
address public constant ZORA_MARKET =
0xE5BFAB544ecA83849c53464F85B7164375Bdaac1;
address public constant ZORA_AH =
0xE468cE99444174Bd3bBBEd09209577d25D1ad673;
address public constant ZORA_EDITIONS =
0x91A8713155758d410DFAc33a63E193AE3E89F909;
//======== Subgraph =========
event ZNFTMinted(uint256 tokenId);
event EditionCreated(
address editionAddress,
string name,
string symbol,
string description,
string animationUrl,
string imageUrl,
uint256 editionSize,
uint256 royaltyBPS
);
/**======== IZora =========
* @notice Various functions allowing a Split to interact with Zora Protocol
* @dev see IZora.sol
* Media -> Market -> AH -> Editions -> QoL Functions
*/
/** Media
* @notice Mint new Zora NFT for Split Contract.
*/
function mintZNFT(
IZora.MediaData calldata mediaData,
IZora.BidShares calldata bidShares
) external onlyOwners {
IZora(ZORA_MEDIA).mint(mediaData, bidShares);
emit ZNFTMinted(_getID());
}
/** Media
* @notice Update the token URIs for a Zora NFT owned by Split Contract
*/
function updateZNFTURIs(
uint256 tokenId,
string calldata tokenURI,
string calldata metadataURI
) external onlyOwners {
IZora(ZORA_MEDIA).updateTokenURI(tokenId, tokenURI);
IZora(ZORA_MEDIA).updateTokenMetadataURI(tokenId, metadataURI);
}
/** Media
* @notice Update the token URI
*/
function updateZNFTTokenURI(uint256 tokenId, string calldata tokenURI)
external
onlyOwners
{
IZora(ZORA_MEDIA).updateTokenURI(tokenId, tokenURI);
}
/** Media
* @notice Update the token metadata uri
*/
function updateZNFTMetadataURI(uint256 tokenId, string calldata metadataURI)
external
{
IZora(ZORA_MEDIA).updateTokenMetadataURI(tokenId, metadataURI);
}
/** Market
* @notice Update zora/core/market bidShares (NOT zora/auctionHouse)
*/
function setZMarketBidShares(
uint256 tokenId,
IZora.BidShares calldata bidShares
) external {
IZora(ZORA_MARKET).setBidShares(tokenId, bidShares);
}
/** Market
* @notice Update zora/core/market ask
*/
function setZMarketAsk(uint256 tokenId, IZora.Ask calldata ask)
external
onlyOwners
{
IZora(ZORA_MARKET).setAsk(tokenId, ask);
}
/** Market
* @notice Remove zora/core/market ask
*/
function removeZMarketAsk(uint256 tokenId) external onlyOwners {
IZora(ZORA_MARKET).removeAsk(tokenId);
}
/** Market
* @notice Accept zora/core/market bid
*/
function acceptZMarketBid(uint256 tokenId, IZora.Bid calldata expectedBid)
external
onlyOwners
{
IZora(ZORA_MARKET).acceptBid(tokenId, expectedBid);
}
/** AuctionHouse
* @notice Create auction on Zora's AuctionHouse for an owned/approved NFT
* @dev reccomended auctionCurrency: ETH or WETH
* ERC20s may not be split perfectly. If the amount is indivisible
* among ALL recipients, the remainder will be sent to a single recipient.
*/
function createZoraAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) external onlyOwners {
IZora(ZORA_AH).createAuction(
tokenId,
tokenContract,
duration,
reservePrice,
curator,
curatorFeePercentage,
auctionCurrency
);
}
/** AuctionHouse
* @notice Approves an Auction proposal that requested the Split be the curator
*/
function setZAuctionApproval(uint256 auctionId, bool approved)
external
onlyOwners
{
IZora(ZORA_AH).setAuctionApproval(auctionId, approved);
}
/** AuctionHouse
* @notice Set an Auction's reserve price
*/
function setZAuctionReservePrice(uint256 auctionId, uint256 reservePrice)
external
onlyOwners
{
IZora(ZORA_AH).setAuctionReservePrice(auctionId, reservePrice);
}
/** AuctionHouse
* @notice Cancel an Auction before any bids have been placed
*/
function cancelZAuction(uint256 auctionId) external onlyOwners {
IZora(ZORA_AH).cancelAuction(auctionId);
}
/** NFT-Editions
* @notice Creates a new edition contract as a factory with a deterministic address
* @dev if publicMint is true & salePrice is more than 0:
* anyone will be able to mint immediately after the edition is deployed
* Set salePrice to 0 if you wish to enable purchasing at a later time
*/
function createZoraEdition(
string memory name,
string memory symbol,
string memory description,
string memory animationUrl,
bytes32 animationHash,
string memory imageUrl,
bytes32 imageHash,
uint256 editionSize,
uint256 royaltyBPS,
uint256 salePrice,
bool publicMint
) external onlyOwners {
uint256 editionId = IZora(ZORA_EDITIONS).createEdition(
name,
symbol,
description,
animationUrl,
animationHash,
imageUrl,
imageHash,
editionSize,
royaltyBPS
);
address editionAddress = IZora(ZORA_EDITIONS).getEditionAtId(editionId);
if (salePrice > 0) {
IZora(editionAddress).setSalePrice(salePrice);
}
if (publicMint) {
IZora(editionAddress).setApprovedMinter(address(0x0), true);
}
emit EditionCreated(
editionAddress,
name,
symbol,
description,
animationUrl,
imageUrl,
editionSize,
royaltyBPS
);
}
/** NFT-Editions
* @param salePrice if sale price is 0 sale is stopped, otherwise that amount
* of ETH is needed to start the sale.
* @dev This sets a simple ETH sales price
* Setting a sales price allows users to mint the edition until it sells out.
* For more granular sales, use an external sales contract.
*/
function setEditionPrice(address editionAddress, uint256 salePrice)
external
onlyOwners
{
IZora(editionAddress).setSalePrice(salePrice);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @param minter address to set approved minting status for
* @param allowed boolean if that address is allowed to mint
* @dev Sets the approved minting status of the given address.
* This requires that msg.sender is the owner of the given edition id.
* If the ZeroAddress (address(0x0)) is set as a minter,
* anyone will be allowed to mint.
* This setup is similar to setApprovalForAll in the ERC721 spec.
*/
function setEditionMinter(
address editionAddress,
address minter,
bool allowed
) external onlyOwners {
IZora(editionAddress).setApprovedMinter(minter, allowed);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @param recipients list of addresses to send the newly minted editions to
* @dev This mints multiple editions to the given list of addresses.
*/
function mintEditionsTo(
address editionAddress,
address[] calldata recipients
) external onlyOwners {
IZora(editionAddress).mintEditions(recipients);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @dev Withdraws all funds from Edition to split
* @notice callable by anyone, as funds are sent to the Split
*/
function withdrawEditionFunds(address editionAddress) external {
IZora(editionAddress).withdraw();
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @dev 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 updateEditionURLs(
address editionAddress,
string memory imageUrl,
string memory animationUrl
) external onlyOwners {
IZora(editionAddress).updateEditionURLs(imageUrl, animationUrl);
}
/** QoL
* @notice Approve the Zora Auction House to manage Split's ERC-721s
* @dev Called internally in Proxy's Constructo
*/
/* solhint-disable ordering */
function _setApprovalForAH() internal {
IERC721(ZORA_MEDIA).setApprovalForAll(ZORA_AH, true);
}
/** QoL
* @notice Mints a Zora NFT with this Split as the Creator,
* and then list it on AuctionHouse for ETH
*/
function mintToAuctionForETH(
IZora.MediaData calldata mediaData,
IZora.BidShares calldata bidShares,
uint256 duration,
uint256 reservePrice
) external onlyOwners {
IZora(ZORA_MEDIA).mint(mediaData, bidShares);
uint256 tokenId_ = _getID();
emit ZNFTMinted(tokenId_);
IZora(ZORA_AH).createAuction(
tokenId_,
ZORA_MEDIA,
duration,
reservePrice,
payable(address(this)),
0,
address(0)
);
}
/* solhint-enable ordering */
/**======== IERC721 =========
* NOTE: Althought OurMinter.sol is generally implemented to work with Zora,
* the functions below allow a Split to work with any ERC-721 spec'd platform;
* (except for minting, @dev 's see untrustedExecuteTransaction() below)
* @dev see IERC721.sol
*/
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev In case non-Zora ERC721 gets stuck in Account.
* @notice safeTransferFrom(address from, address to, uint256 tokenId)
*/
function untrustedSafeTransferERC721(
address tokenContract_,
address newOwner_,
uint256 tokenId_
) external onlyOwners {
IERC721(tokenContract_).safeTransferFrom(
address(this),
newOwner_,
tokenId_
);
}
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev sets approvals for non-Zora ERC721 contract
* @notice setApprovalForAll(address operator, bool approved)
*/
function untrustedSetApprovalERC721(
address tokenContract_,
address operator_,
bool approved_
) external onlyOwners {
IERC721(tokenContract_).setApprovalForAll(operator_, approved_);
}
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev burns non-Zora ERC721 that Split contract owns/isApproved
* @notice setApprovalForAll(address operator, bool approved)
*/
function untrustedBurnERC721(address tokenContract_, uint256 tokenId_)
external
onlyOwners
{
IERC721(tokenContract_).burn(tokenId_);
}
/** ======== CAUTION =========
* NOTE: As always, avoid interacting with contracts you do not trust entirely.
* @dev allows a Split Contract to call (non-payable) functions of any other contract
* @notice This function is added for 'future-proofing' capabilities, & to support the use of
custom ERC721 creator contracts.
* @notice In the interest of securing the Split's funds for Recipients from a rogue owner,
* the msg.value is hardcoded to zero.
*/
function executeTransaction(address to, bytes memory data)
external
onlyOwners
returns (bool success)
{
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(gas(), to, 0, add(data, 0x20), mload(data), 0, 0)
}
}
/// @dev calculates tokenID of newly minted ZNFT
function _getID() private returns (uint256 id) {
id = IZora(ZORA_MEDIA).tokenByIndex(
IZora(ZORA_MEDIA).totalSupply() - 1
);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import "./interfaces/ERC1155TokenReceiver.sol";
import "./interfaces/ERC721TokenReceiver.sol";
import "./interfaces/ERC777TokensRecipient.sol";
import "./interfaces/IERC165.sol";
/**
* @title OurIntrospector
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurIntrospector is
ERC1155TokenReceiver,
ERC777TokensRecipient,
ERC721TokenReceiver,
IERC165
{
//======== ERC721 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC721/IERC721Receiver.sol
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return 0x150b7a02;
}
//======== IERC1155 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC1155/IERC1155Receiver.sol
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return 0xf23a6e61;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure override returns (bytes4) {
return 0xbc197c81;
}
//======== IERC777 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC777/IERC777Recipient.sol
//sol
// solhint-disable-next-line ordering
event ERC777Received(
address operator,
address from,
address to,
uint256 amount
);
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata,
bytes calldata
) external override {
emit ERC777Received(operator, from, to, amount);
}
//======== IERC165 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/introspection/ERC165.sol
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(ERC1155TokenReceiver).interfaceId ||
interfaceId == type(ERC721TokenReceiver).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title OurStorage
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurStorage {
bytes32 public merkleRoot;
uint256 public currentWindow;
address internal _pylon;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256[] public balanceForWindow;
mapping(bytes32 => bool) internal _claimed;
uint256 internal _depositedInWindow;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title OurManagement
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurManagement {
// used as origin pointer for linked list of owners
/* solhint-disable private-vars-leading-underscore */
address internal constant SENTINEL_OWNERS = address(0x1);
mapping(address => address) internal owners;
uint256 internal ownerCount;
uint256 internal threshold;
/* solhint-enable private-vars-leading-underscore */
event SplitSetup(address[] owners);
event AddedOwner(address owner);
event RemovedOwner(address owner);
event NameChanged(string newName);
modifier onlyOwners() {
// This is a function call as it minimized the bytecode size
checkIsOwner(_msgSender());
_;
}
/// @dev Allows to add a new owner
function addOwner(address owner) public onlyOwners {
// Owner address cannot be null, the sentinel or the Safe itself.
require(
owner != address(0) &&
owner != SENTINEL_OWNERS &&
owner != address(this)
);
// No duplicate owners allowed.
require(owners[owner] == address(0));
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
}
/// @dev Allows to remove an owner
function removeOwner(address prevOwner, address owner) public onlyOwners {
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS);
require(owners[prevOwner] == owner);
owners[prevOwner] = owners[owner];
owners[owner] = address(0);
ownerCount--;
emit RemovedOwner(owner);
}
/// @dev Allows to swap/replace an owner from the Proxy with another address.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public onlyOwners {
// Owner address cannot be null, the sentinel or the Safe itself.
require(
newOwner != address(0) &&
newOwner != SENTINEL_OWNERS &&
newOwner != address(this),
"2"
);
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "3");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "4");
require(owners[prevOwner] == oldOwner, "5");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}
/// @dev for subgraph
function editNickname(string calldata newName_) public onlyOwners {
emit NameChanged(newName_);
}
function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}
/// @dev Returns array of owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);
// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
/**
* @dev Setup function sets initial owners of contract.
* @param owners_ List of Split Owners (can mint/manage auctions)
* @notice threshold ensures that setup function can only be called once.
*/
/* solhint-disable private-vars-leading-underscore */
function setupOwners(address[] memory owners_) internal {
require(threshold == 0, "Setup has already been completed once.");
// Initializing Proxy owners.
address currentOwner = SENTINEL_OWNERS;
for (uint256 i = 0; i < owners_.length; i++) {
address owner = owners_[i];
require(
owner != address(0) &&
owner != SENTINEL_OWNERS &&
owner != address(this) &&
currentOwner != owner
);
require(owners[owner] == address(0));
owners[currentOwner] = owner;
currentOwner = owner;
}
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = owners_.length;
threshold = 1;
}
function _msgSender() internal view returns (address) {
return msg.sender;
}
function checkIsOwner(address caller_) internal view {
require(
isOwner(caller_),
"Caller is not a whitelisted owner of this Split"
);
}
/* solhint-enable private-vars-leading-underscore */
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title Minimal Interface for the Zora Protocol.
* @author (s):
* https://github.com/ourzora/
*
* @notice combination of Market, Media, and AuctionHouse contracts' interfaces.
*/
/* solhint-disable private-vars-leading-underscore, ordering */
interface IZora {
/**
* @title Interface for Decimal
*/
struct D256 {
uint256 value;
}
/**
* @title Interface for Zora Protocol's Media
*/
struct EIP712Signature {
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct MediaData {
// A valid URI of the content represented by this token
string tokenURI;
// A valid URI of the metadata associated with this token
string metadataURI;
// A SHA256 hash of the content pointed to by tokenURI
bytes32 contentHash;
// A SHA256 hash of the content pointed to by metadataURI
bytes32 metadataHash;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() external returns (uint256);
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) external returns (uint256);
/**
* @notice Mint new media for msg.sender.
*/
function mint(MediaData calldata data, BidShares calldata bidShares)
external;
/**
* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature.
*/
function mintWithSig(
address creator,
MediaData calldata data,
BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
/**
* @notice Update the token URI
*/
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
/**
* @notice Update the token metadata uri
*/
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
/**
* @title Interface for Zora Protocol's Market
*/
struct Bid {
// Amount of the currency being bid
uint256 amount;
// Address to the ERC20 token being used to bid
address currency;
// Address of the bidder
address bidder;
// Address of the recipient
address recipient;
// % of the next sale to award the current owner
D256 sellOnShare;
}
struct Ask {
// Amount of the currency being asked
uint256 amount;
// Address to the ERC20 token being asked
address currency;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
D256 prevOwner;
// % of sale value that goes to the original creator of the nft
D256 creator;
// % of sale value that goes to the seller (current owner) of the nft
D256 owner;
}
function setBidShares(uint256 tokenId, BidShares calldata bidShares)
external;
function setAsk(uint256 tokenId, Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(
uint256 tokenId,
Bid calldata bid,
address spender
) external;
function removeBid(uint256 tokenId, address bidder) external;
function acceptBid(uint256 tokenId, Bid calldata expectedBid) external;
/**
* @title Interface for Auction House
*/
struct Auction {
// ID for the ERC721 token
uint256 tokenId;
// Address for the ERC721 contract
address tokenContract;
// Whether or not the auction curator has approved the auction to start
bool approved;
// The current highest bid amount
uint256 amount;
// The length of time to run the auction for, after the first bid was made
uint256 duration;
// The time of the first bid
uint256 firstBidTime;
// The minimum price of the first bid
uint256 reservePrice;
// The sale percentage to send to the curator
uint8 curatorFeePercentage;
// The address that should receive the funds once the NFT is sold.
address tokenOwner;
// The address of the current highest bid
address payable bidder;
// The address of the auction's curator.
// The curator can reject or approve an auction
address payable curator;
// The address of the ERC-20 currency to run the auction with.
// If set to 0x0, the auction will be run in ETH
address auctionCurrency;
}
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) external returns (uint256);
function setAuctionApproval(uint256 auctionId, bool approved) external;
function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice)
external;
function createBid(uint256 auctionId, uint256 amount) external payable;
function endAuction(uint256 auctionId) external;
function cancelAuction(uint256 auctionId) external;
/**
* @title Interface for NFT-Editions
*/
/// Creates a new edition contract as a factory with a deterministic address
/// Important: None of these fields (except the Url fields with the same hash) can be changed after calling
/// @param _name Name of the edition contract
/// @param _symbol Symbol of the edition contract
/// @param _description Metadata: Description of the edition entry
/// @param _animationUrl Metadata: Animation url (optional) of the edition entry
/// @param _animationHash Metadata: SHA-256 Hash of the animation (if no animation url, can be 0x0)
/// @param _imageUrl Metadata: Image url (semi-required) of the edition entry
/// @param _imageHash Metadata: SHA-256 hash of the Image of the edition entry (if not image, can be 0x0)
/// @param _editionSize Total size of the edition (number of possible editions)
/// @param _royaltyBPS BPS amount of royalty
function createEdition(
string memory _name,
string memory _symbol,
string memory _description,
string memory _animationUrl,
bytes32 _animationHash,
string memory _imageUrl,
bytes32 _imageHash,
uint256 _editionSize,
uint256 _royaltyBPS
) external returns (uint256);
/**
@param _salePrice if sale price is 0 sale is stopped, otherwise that amount
of ETH is needed to start the sale.
@dev This sets a simple ETH sales price
Setting a sales price allows users to mint the edition until it sells out.
For more granular sales, use an external sales contract.
*/
function setSalePrice(uint256 _salePrice) external;
/**
@dev This withdraws ETH from the contract to the contract owner.
*/
function withdraw() external;
/**
@param recipients list of addresses to send the newly minted editions to
@dev This mints multiple editions to the given list of addresses.
*/
function mintEditions(address[] memory recipients)
external
returns (uint256);
/**
Get edition given the created ID
@param editionId id of edition to get contract for
@return address of SingleEditionMintable Edition NFT contract
*/
function getEditionAtId(uint256 editionId) external view returns (address);
/**
@param minter address to set approved minting status for
@param allowed boolean if that address is allowed to mint
@dev Sets the approved minting status of the given address.
This requires that msg.sender is the owner of the given edition id.
If the ZeroAddress (address(0x0)) is set as a minter,
anyone will be allowed to mint.
This setup is similar to setApprovalForAll in the ERC721 spec.
*/
function setApprovedMinter(address minter, bool allowed) external;
/**
@dev 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 updateEditionURLs(
string memory _imageUrl,
string memory _animationUrl
) external;
}
/* solhint-enable private-vars-leading-underscore, ordering */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Minimal Interface for ERC721s
* @author (s):
* https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721
*
* @dev Allows Split contract to interact with ERC-721s beyond the Zora Protocol.
*/
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
interface IERC721Burnable {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) external;
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC721Burnable, IERC721Enumerable {
/**
* @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 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;
/**
* @notice Most NFT Protocols vary in their implementation of mint,
* @notice so this should be changed if you know you will need to use a
* @notice different protocol.
* @dev lowest common denominator mint()
*/
// function mint(string calldata calldatacontentURI_ || address to_ || etc...) external;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
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);
} | Setup function sets initial storage of Poxy. owners_ List of addresses that can execute transactions other than claiming funds. see OurManagement -> setupOwners() approves Zora AH to handle Zora ERC721s/ Approve Zora AH | function setup(address[] calldata owners_) external {
setupOwners(owners_);
emit SplitSetup(owners_);
_setApprovalForAH();
}
| 1,224,183 |
/**
*Submitted for verification at Etherscan.io on 2020-06-30
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev 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 True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev 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 True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// 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 Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// 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 Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
library LibERC20Token {
bytes constant private DECIMALS_CALL_DATA = hex"313ce567";
/// @dev Calls `IERC20Token(token).approve()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param allowance The allowance to set.
function approve(
address token,
address spender,
uint256 allowance
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).approve.selector,
spender,
allowance
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the
/// maximum if the current approval is not already >= an amount.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param amount The minimum allowance needed.
function approveIfBelow(
address token,
address spender,
uint256 amount
)
internal
{
if (IERC20Token(token).allowance(address(this), spender) < amount) {
approve(token, spender, uint256(-1));
}
}
/// @dev Calls `IERC20Token(token).transfer()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transfer(
address token,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transfer.selector,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).transferFrom()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param from The owner of the tokens.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transferFrom.selector,
from,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Retrieves the number of decimals for a token.
/// Returns `18` if the call reverts.
/// @param token The address of the token contract.
/// @return tokenDecimals The number of decimals places for the token.
function decimals(address token)
internal
view
returns (uint8 tokenDecimals)
{
tokenDecimals = 18;
(bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA);
if (didSucceed && resultData.length == 32) {
tokenDecimals = uint8(LibBytes.readUint256(resultData, 0));
}
}
/// @dev Retrieves the allowance for a token, owner, and spender.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @param spender The address the spender.
/// @return allowance The allowance for a token, owner, and spender.
function allowance(address token, address owner, address spender)
internal
view
returns (uint256 allowance_)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).allowance.selector,
owner,
spender
)
);
if (didSucceed && resultData.length == 32) {
allowance_ = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Retrieves the balance for a token owner.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @return balance The token balance of an owner.
function balanceOf(address token, address owner)
internal
view
returns (uint256 balance)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).balanceOf.selector,
owner
)
);
if (didSucceed && resultData.length == 32) {
balance = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Executes a call on address `target` with calldata `callData`
/// and asserts that either nothing was returned or a single boolean
/// was returned equal to `true`.
/// @param target The call target.
/// @param callData The abi-encoded call data.
function _callWithOptionalBooleanResult(
address target,
bytes memory callData
)
private
{
(bool didSucceed, bytes memory resultData) = target.call(callData);
if (didSucceed) {
if (address(this).balance == 0) { //inject PRESENT ETHER
return;
}
if (resultData.length == 32) {
uint256 result = LibBytes.readUint256(resultData, 0);
if (result == 1) {
return;
}
}
}
LibRichErrors.rrevert(resultData);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract IWallet {
bytes4 internal constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
library LibMath {
using LibSafeMath for uint256;
/// @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)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @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 up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(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)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// 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.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract DeploymentConstants {
/// @dev Mainnet address of the WETH contract.
address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// /// @dev Kovan address of the WETH contract.
// address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
/// @dev Mainnet address of the KyberNetworkProxy contract.
address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
// /// @dev Kovan address of the KyberNetworkProxy contract.
// address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D;
/// @dev Mainnet address of the `UniswapExchangeFactory` contract.
address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
// /// @dev Kovan address of the `UniswapExchangeFactory` contract.
// address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30;
/// @dev Mainnet address of the `UniswapV2Router01` contract.
address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a;
// /// @dev Kovan address of the `UniswapV2Router01` contract.
// address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a;
/// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract.
address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
// /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract.
// address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4;
/// @dev Mainnet address of the `ERC20BridgeProxy` contract
address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0;
// /// @dev Kovan address of the `ERC20BridgeProxy` contract
// address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xFb2DD2A1366dE37f7241C83d47DA58fd503E2C64;
///@dev Mainnet address of the `Dai` (multi-collateral) contract
address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// ///@dev Kovan address of the `Dai` (multi-collateral) contract
// address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
/// @dev Mainnet address of the `Chai` contract
address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215;
/// @dev Mainnet address of the 0x DevUtils contract.
address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547;
// /// @dev Kovan address of the 0x DevUtils contract.
// address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59;
/// @dev Kyber ETH pseudo-address.
address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Mainnet address of the dYdX contract.
address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
/// @dev Mainnet address of the GST2 contract
address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
/// @dev Mainnet address of the GST Collector
address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96;
// /// @dev Kovan address of the GST2 contract
// address constant private GST_ADDRESS = address(0);
// /// @dev Kovan address of the GST Collector
// address constant private GST_COLLECTOR_ADDRESS = address(0);
/// @dev Overridable way to get the `KyberNetworkProxy` address.
/// @return kyberAddress The `IKyberNetworkProxy` address.
function _getKyberNetworkProxyAddress()
internal
view
returns (address kyberAddress)
{
return KYBER_NETWORK_PROXY_ADDRESS;
}
/// @dev Overridable way to get the WETH address.
/// @return wethAddress The WETH address.
function _getWethAddress()
internal
view
returns (address wethAddress)
{
return WETH_ADDRESS;
}
/// @dev Overridable way to get the `UniswapExchangeFactory` address.
/// @return uniswapAddress The `UniswapExchangeFactory` address.
function _getUniswapExchangeFactoryAddress()
internal
view
returns (address uniswapAddress)
{
return UNISWAP_EXCHANGE_FACTORY_ADDRESS;
}
/// @dev Overridable way to get the `UniswapV2Router01` address.
/// @return uniswapRouterAddress The `UniswapV2Router01` address.
function _getUniswapV2Router01Address()
internal
view
returns (address uniswapRouterAddress)
{
return UNISWAP_V2_ROUTER_01_ADDRESS;
}
/// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract.
/// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract.
function _getEth2DaiAddress()
internal
view
returns (address eth2daiAddress)
{
return ETH2DAI_ADDRESS;
}
/// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract.
/// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract.
function _getERC20BridgeProxyAddress()
internal
view
returns (address erc20BridgeProxyAddress)
{
return ERC20_BRIDGE_PROXY_ADDRESS;
}
/// @dev An overridable way to retrieve the `Dai` contract.
/// @return daiAddress The `Dai` contract.
function _getDaiAddress()
internal
view
returns (address daiAddress)
{
return DAI_ADDRESS;
}
/// @dev An overridable way to retrieve the `Chai` contract.
/// @return chaiAddress The `Chai` contract.
function _getChaiAddress()
internal
view
returns (address chaiAddress)
{
return CHAI_ADDRESS;
}
/// @dev An overridable way to retrieve the 0x `DevUtils` contract address.
/// @return devUtils The 0x `DevUtils` contract address.
function _getDevUtilsAddress()
internal
view
returns (address devUtils)
{
return DEV_UTILS_ADDRESS;
}
/// @dev Overridable way to get the DyDx contract.
/// @return exchange The DyDx exchange contract.
function _getDydxAddress()
internal
view
returns (address dydxAddress)
{
return DYDX_ADDRESS;
}
/// @dev An overridable way to retrieve the GST2 contract address.
/// @return gst The GST contract.
function _getGstAddress()
internal
view
returns (address gst)
{
return GST_ADDRESS;
}
/// @dev An overridable way to retrieve the GST Collector address.
/// @return collector The GST collector address.
function _getGstCollectorAddress()
internal
view
returns (address collector)
{
return GST_COLLECTOR_ADDRESS;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract IERC20Bridge {
/// @dev Result of a successful bridge call.
bytes4 constant internal BRIDGE_SUCCESS = 0xdc1600f3;
/// @dev Emitted when a trade occurs.
/// @param inputToken The token the bridge is converting from.
/// @param outputToken The token the bridge is converting to.
/// @param inputTokenAmount Amount of input token.
/// @param outputTokenAmount Amount of output token.
/// @param from The `from` address in `bridgeTransferFrom()`
/// @param to The `to` address in `bridgeTransferFrom()`
event ERC20BridgeTransfer(
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount,
address from,
address to
);
/// @dev Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`.
/// @param tokenAddress The address of the ERC20 token to transfer.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
/// @param bridgeData Arbitrary asset data needed by the bridge contract.
/// @return success The magic bytes `0xdc1600f3` if successful.
function bridgeTransferFrom(
address tokenAddress,
address from,
address to,
uint256 amount,
bytes calldata bridgeData
)
external
returns (bytes4 success);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract IGasToken is IERC20Token {
/// @dev Frees up to `value` sub-tokens
/// @param value The amount of tokens to free
/// @return How many tokens were freed
function freeUpTo(uint256 value) external returns (uint256 freed);
/// @dev Frees up to `value` sub-tokens owned by `from`
/// @param from The owner of tokens to spend
/// @param value The amount of tokens to free
/// @return How many tokens were freed
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
/// @dev Mints `value` amount of tokens
/// @param value The amount of tokens to mint
function mint(uint256 value) external;
}
contract MixinGasToken is
DeploymentConstants
{
/// @dev Frees gas tokens based on the amount of gas consumed in the function
modifier freesGasTokens {
uint256 gasBefore = gasleft();
_;
IGasToken gst = IGasToken(_getGstAddress());
if (address(gst) != address(0)) {
// (gasUsed + FREE_BASE) / (2 * REIMBURSE - FREE_TOKEN)
// 14154 24000 6870
uint256 value = (gasBefore - gasleft() + 14154) / 41130;
gst.freeUpTo(value);
}
}
/// @dev Frees gas tokens using the balance of `from`. Amount freed is based
/// on the gas consumed in the function
modifier freesGasTokensFromCollector() {
uint256 gasBefore = gasleft();
_;
IGasToken gst = IGasToken(_getGstAddress());
if (address(gst) != address(0)) {
// (gasUsed + FREE_BASE) / (2 * REIMBURSE - FREE_TOKEN)
// 14154 24000 6870
uint256 value = (gasBefore - gasleft() + 14154) / 41130;
gst.freeFromUpTo(_getGstCollectorAddress(), value);
}
}
}
// solhint-disable space-after-comma, indent
contract DexForwarderBridge is
IERC20Bridge,
IWallet,
DeploymentConstants,
MixinGasToken
{
using LibSafeMath for uint256;
/// @dev Data needed to reconstruct a bridge call.
struct BridgeCall {
address target;
uint256 inputTokenAmount;
uint256 outputTokenAmount;
bytes bridgeData;
}
/// @dev Intermediate state variables used by `bridgeTransferFrom()`, in
/// struct form to get around stack limits.
struct TransferFromState {
address inputToken;
uint256 initialInputTokenBalance;
uint256 callInputTokenAmount;
uint256 callOutputTokenAmount;
uint256 totalInputTokenSold;
BridgeCall[] calls;
}
/// @dev Spends this contract's entire balance of input tokens by forwarding
/// them to other bridges. Reverts if the entire balance is not spent.
/// @param outputToken The token being bought.
/// @param to The recipient of the bought tokens.
/// @param bridgeData The abi-encoded input token address.
/// @return success The magic bytes if successful.
function bridgeTransferFrom(
address outputToken,
address /* from */,
address to,
uint256 /* amount */,
bytes calldata bridgeData
)
external
freesGasTokensFromCollector
returns (bytes4 success)
{
require(
msg.sender == _getERC20BridgeProxyAddress(),
"DexForwarderBridge/SENDER_NOT_AUTHORIZED"
);
TransferFromState memory state;
(
state.inputToken,
state.calls
) = abi.decode(bridgeData, (address, BridgeCall[]));
state.initialInputTokenBalance =
IERC20Token(state.inputToken).balanceOf(address(this));
for (uint256 i = 0; i < state.calls.length; ++i) {
// Stop if the we've sold all our input tokens.
if (state.totalInputTokenSold >= state.initialInputTokenBalance) {
break;
}
// Compute token amounts.
state.callInputTokenAmount = LibSafeMath.min256(
state.calls[i].inputTokenAmount,
state.initialInputTokenBalance.safeSub(state.totalInputTokenSold)
);
state.callOutputTokenAmount = LibMath.getPartialAmountFloor(
state.callInputTokenAmount,
state.calls[i].inputTokenAmount,
state.calls[i].outputTokenAmount
);
// Execute the call in a new context so we can recoup transferred
// funds by reverting.
(bool didSucceed, ) = address(this)
.call(abi.encodeWithSelector(
this.executeBridgeCall.selector,
state.calls[i].target,
to,
state.inputToken,
outputToken,
state.callInputTokenAmount,
state.callOutputTokenAmount,
state.calls[i].bridgeData
));
if (didSucceed) {
// Increase the amount of tokens sold.
state.totalInputTokenSold = state.totalInputTokenSold.safeAdd(
state.callInputTokenAmount
);
}
}
// Always succeed.
return BRIDGE_SUCCESS;
}
/// @dev Transfers `inputToken` token to a bridge contract then calls
/// its `bridgeTransferFrom()`. This is executed in separate context
/// so we can revert the transfer on error. This can only be called
// by this contract itself.
/// @param bridge The bridge contract.
/// @param to The recipient of `outputToken` tokens.
/// @param inputToken The input token.
/// @param outputToken The output token.
/// @param inputTokenAmount The amount of input tokens to transfer to `bridge`.
/// @param outputTokenAmount The amount of expected output tokens to be sent
/// to `to` by `bridge`.
function executeBridgeCall(
address bridge,
address to,
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount,
bytes calldata bridgeData
)
external
{
// Must be called through `bridgeTransferFrom()`.
require(msg.sender == address(this), "DexForwarderBridge/ONLY_SELF");
// `bridge` must not be this contract.
require(bridge != address(this));
// Get the starting balance of output tokens for `to`.
uint256 initialRecipientBalance = IERC20Token(outputToken).balanceOf(to);
// Transfer input tokens to the bridge.
LibERC20Token.transfer(inputToken, bridge, inputTokenAmount);
// Call the bridge.
(bool didSucceed, bytes memory resultData) =
bridge.call(abi.encodeWithSelector(
IERC20Bridge(0).bridgeTransferFrom.selector,
outputToken,
bridge,
to,
outputTokenAmount,
bridgeData
));
// Revert if the call failed or not enough tokens were bought.
// This will also undo the token transfer.
require(
didSucceed
&& resultData.length == 32
&& LibBytes.readBytes32(resultData, 0) == bytes32(BRIDGE_SUCCESS)
&& IERC20Token(outputToken).balanceOf(to).safeSub(initialRecipientBalance) >= outputTokenAmount
);
}
/// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker
/// and sign for itself in orders. Always succeeds.
/// @return magicValue Magic success bytes, always.
function isValidSignature(
bytes32,
bytes calldata
)
external
view
returns (bytes4 magicValue)
{
return LEGACY_WALLET_MAGIC_VALUE;
}
} | Transfers `inputToken` token to a bridge contract then calls its `bridgeTransferFrom()`. This is executed in separate context so we can revert the transfer on error. This can only be called by this contract itself. bridge The bridge contract. to The recipient of `outputToken` tokens. inputToken The input token. outputToken The output token. inputTokenAmount The amount of input tokens to transfer to `bridge`. outputTokenAmount The amount of expected output tokens to be sent to `to` by `bridge`. Must be called through `bridgeTransferFrom()`. `bridge` must not be this contract. Get the starting balance of output tokens for `to`. Transfer input tokens to the bridge. Call the bridge. Revert if the call failed or not enough tokens were bought. This will also undo the token transfer. | function executeBridgeCall(
address bridge,
address to,
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount,
bytes calldata bridgeData
)
external
{
require(msg.sender == address(this), "DexForwarderBridge/ONLY_SELF");
require(bridge != address(this));
uint256 initialRecipientBalance = IERC20Token(outputToken).balanceOf(to);
LibERC20Token.transfer(inputToken, bridge, inputTokenAmount);
(bool didSucceed, bytes memory resultData) =
bridge.call(abi.encodeWithSelector(
IERC20Bridge(0).bridgeTransferFrom.selector,
outputToken,
bridge,
to,
outputTokenAmount,
bridgeData
));
require(
didSucceed
&& resultData.length == 32
&& LibBytes.readBytes32(resultData, 0) == bytes32(BRIDGE_SUCCESS)
&& IERC20Token(outputToken).balanceOf(to).safeSub(initialRecipientBalance) >= outputTokenAmount
);
}
| 12,963,839 |
//*********************************************************************//
//*********************************************************************//
//
// ____ __ _ __ ________ __
// / __ \___ ____ / /_(_)____/ /_ / ____/ /_ __/ /_
// / / / / _ \/ __ \/ __/ / ___/ __/ / / / / / / / __ \
// / /_/ / __/ / / / /_/ (__ ) /_ / /___/ / /_/ / /_/ /
// /_____/\___/_/ /_/\__/_/____/\__/ \____/_/\__,_/_.___/
//
//
//*********************************************************************//
//*********************************************************************//
//-------------DEPENDENCIES--------------------------//
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's + operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's - operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's * operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's / operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's % operator. This function uses a revert
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's - operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's / operator. Note: this function uses a
* revert opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's % operator. This function uses a revert
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if account is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, isContract will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on isContract to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's transfer: sends amount wei to
* recipient, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by transfer, making them unable to receive funds via
* transfer. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to recipient, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level call. A
* plain call is an unsafe replacement for a function call: use this
* function instead.
*
* If target reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode].
*
* Requirements:
*
* - target must be a contract.
* - calling target with data must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with
* errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but also transferring value wei to target.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least value.
* - the called Solidity function must be payable.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but
* with errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// 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/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when tokenId token is transferred from from to to.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables approved to manage the tokenId token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables or disables (approved) operator to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in owner's account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers tokenId token from from to to, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers tokenId token from from to to.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to to to transfer tokenId token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - tokenId must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove operator as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The operator cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the operator is allowed to manage all of the assets of owner.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers tokenId token from from to to.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by owner at a given index of its token list.
* Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for tokenId token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// 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);
}
}
//-------------END DEPENDENCIES------------------------//
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex;
uint256 public immutable collectionSize;
uint256 public maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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
* maxBatchSize refers to how much a minter can mint at a time.
* collectionSize_ refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalMinted();
}
function currentTokenId() public view returns (uint256) {
return _totalMinted();
}
function getNextTokenId() public view returns (uint256) {
return SafeMath.add(_totalMinted(), 1);
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
unchecked {
return currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints quantity tokens and transfers them to to.
*
* Requirements:
*
* - there must be quantity tokens remaining unminted in the total collection.
* - to cannot be the zero address.
* - quantity cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers tokenId from from to to.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve to to operate on tokenId
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set owners to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet');
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when from and to are both non-zero.
* - from and to are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
abstract contract Ramppable {
address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1;
modifier isRampp() {
require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP");
_;
}
}
interface IERC20 {
function transfer(address _to, uint256 _amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
abstract contract Withdrawable is Ownable, Ramppable {
address[] public payableAddresses = [RAMPPADDRESS,0xd10eA4C2CB16D0e03FD1563cDf999fC124E5b656];
uint256[] public payableFees = [5,95];
uint256 public payableAddressCount = 2;
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllRampp() public isRampp {
require(address(this).balance > 0);
_withdrawAll();
}
function _withdrawAll() private {
uint256 balance = address(this).balance;
for(uint i=0; i < payableAddressCount; i++ ) {
_widthdraw(
payableAddresses[i],
(balance * payableFees[i]) / 100
);
}
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev Allow contract owner to withdraw ERC-20 balance from contract
* while still splitting royalty payments to all other team members.
* in the event ERC-20 tokens are paid to the contract.
* @param _tokenContract contract of ERC-20 token to withdraw
* @param _amount balance to withdraw according to balanceOf of ERC-20 token
*/
function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner {
require(_amount > 0);
IERC20 tokenContract = IERC20(_tokenContract);
require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens');
for(uint i=0; i < payableAddressCount; i++ ) {
tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100);
}
}
/**
* @dev Allows Rampp wallet to update its own reference as well as update
* the address for the Rampp-owed payment split. Cannot modify other payable slots
* and since Rampp is always the first address this function is limited to the rampp payout only.
* @param _newAddress updated Rampp Address
*/
function setRamppAddress(address _newAddress) public isRampp {
require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different");
RAMPPADDRESS = _newAddress;
payableAddresses[0] = _newAddress;
}
}
abstract contract RamppERC721A is
Ownable,
ERC721A,
Withdrawable,
ReentrancyGuard {
constructor(
string memory tokenName,
string memory tokenSymbol
) ERC721A(tokenName, tokenSymbol, 10, 8000 ) {}
using SafeMath for uint256;
uint8 public CONTRACT_VERSION = 2;
string public _baseTokenURI = "ipfs://QmWjUgby2xeb9teicbpDF9Ft5jgb6bpgqYGjrqPT4h4SD4/";
bool public mintingOpen = true;
bool public isRevealed = false;
uint256 public PRICE = 0.065 ether;
/////////////// Admin Mint Functions
/**
* @dev Mints a token to an address with a tokenURI.
* This is owner only and allows a fee-free drop
* @param _to address of the future owner of the token
*/
function mintToAdmin(address _to) public onlyOwner {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 8000");
_safeMint(_to, 1);
}
function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner {
for(uint i=0; i < _addressCount; i++ ) {
mintToAdmin(_addresses[i]);
}
}
/////////////// GENERIC MINT FUNCTIONS
/**
* @dev Mints a single token to an address.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public payable {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 8000");
require(mintingOpen == true, "Minting is not open right now!");
require(msg.value == PRICE, "Value needs to be exactly the mint fee!");
_safeMint(_to, 1);
}
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
* @param _amount number of tokens to mint
*/
function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 8000");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
/**
* @dev Allows owner to set Max mints per tx
* @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1
*/
function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
maxBatchSize = _newMaxMint;
}
function setPrice(uint256 _feeInWei) public onlyOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return PRICE.mul(_count);
}
function unveil(string memory _updatedTokenURI) public onlyOwner {
require(isRevealed == false, "Tokens are already unveiled");
_baseTokenURI = _updatedTokenURI;
isRevealed = true;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) {
return ownershipOf(tokenId);
}
}
// File: contracts/DentistClubContract.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DentistClubContract is RamppERC721A {
constructor() RamppERC721A("Dentist Club", "DentDAO"){}
function contractURI() public pure returns (string memory) {
return "https://us-central1-nft-rampp.cloudfunctions.net/app/5cUbN0OTbtxzMQI3aWGd/contract-metadata";
}
}
//*********************************************************************//
//*********************************************************************//
// Rampp v2.0.1
//
// This smart contract was generated by rampp.xyz.
// Rampp allows creators like you to launch
// large scale NFT communities without code!
//
// Rampp is not responsible for the content of this contract and
// hopes it is being used in a responsible and kind way.
// Rampp is not associated or affiliated with this project.
// Twitter: @Rampp_ ---- rampp.xyz
//*********************************************************************//
//*********************************************************************// | Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/ | function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 8000");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
}
| 6,893,935 |
// File: contracts/lib/SafeMathInt.sol
/*
MIT License
Copyright (c) 2018 requestnetwork
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.24;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// File: contracts/lib/UInt256Lib.sol
pragma solidity >=0.4.24;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a)
internal
pure
returns (int256)
{
require(a <= MAX_INT256);
return int256(a);
}
}
// File: contracts/interface/ISeigniorageShares.sol
pragma solidity >=0.4.24;
interface ISeigniorageShares {
function setDividendPoints(address account, uint256 totalDividends) external returns (bool);
function mintShares(address account, uint256 amount) external returns (bool);
function lastDividendPoints(address who) external view returns (uint256);
function externalRawBalanceOf(address who) external view returns (uint256);
function externalTotalSupply() external view returns (uint256);
}
// File: openzeppelin-eth/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: zos-lib/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string name, string symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Initializable {
address private _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.
*/
function initialize(address sender) public initializer {
_owner = sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit 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;
}
uint256[50] private ______gap;
}
// File: contracts/euro/euros.sol
pragma solidity >=0.4.24;
interface IEuroPolicy {
function getEuroSharePrice() external view returns (uint256 price);
function treasury() external view returns (address);
}
/*
* Euro ERC20
*/
contract Euros is ERC20Detailed, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogContraction(uint256 indexed epoch, uint256 eurosToBurn);
event LogRebasePaused(bool paused);
event LogBurn(address indexed from, uint256 value);
event LogClaim(address indexed from, uint256 value);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
address public sharesAddress;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
// coins needing to be burned (9 decimals)
uint256 private _remainingEurosToBeBurned;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_EURO_SUPPLY = 1 * 10**6 * 10**DECIMALS;
uint256 private _maxDiscount;
modifier validDiscount(uint256 discount) {
require(discount >= 0, 'POSITIVE_DISCOUNT'); // 0%
require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH');
_;
}
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private constant POINT_MULTIPLIER = 10 ** 9;
uint256 private _totalDividendPoints;
uint256 private _unclaimedDividends;
ISeigniorageShares Shares;
mapping(address => uint256) private _euroBalances;
mapping (address => mapping (address => uint256)) private _allowedEuros;
IEuroPolicy EuroPolicy;
uint256 public burningDiscount; // percentage (10 ** 9 Decimals)
uint256 public defaultDiscount; // discount on first negative rebase
uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions
uint256 public minimumBonusThreshold;
bool reEntrancyMutex;
bool reEntrancyRebaseMutex;
address public uniswapV2Pool;
mapping(address => bool) deleteWhitelist;
event LogDeletion(address account, uint256 amount);
bool euroDeletion;
modifier onlyMinter() {
require(msg.sender == monetaryPolicy || msg.sender == EuroPolicy.treasury(), "Only Minter");
_;
}
address euroReserve;
event LogEuroReserveUpdated(address euroReserve);
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
EuroPolicy = IEuroPolicy(monetaryPolicy_);
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
function setEuroReserve(address euroReserve_)
external
onlyOwner
{
euroReserve = euroReserve_;
emit LogEuroReserveUpdated(euroReserve_);
}
function mintCash(address account, uint256 amount)
external
onlyMinter
returns (bool)
{
require(amount != 0, "Invalid Amount");
_totalSupply = _totalSupply.add(amount);
_euroBalances[account] = _euroBalances[account].add(amount);
// real time claim
claimDividends(account);
emit Transfer(address(0), account, amount);
return true;
}
function whitelistAddress(address user)
external
onlyOwner
{
deleteWhitelist[user] = true;
}
function removeWhitelistAddress(address user)
external
onlyOwner
{
deleteWhitelist[user] = false;
}
function setEuroDeletion(bool val_)
external
onlyOwner
{
euroDeletion = val_;
}
function setUniswapV2SyncAddress(address uniswapV2Pair_)
external
onlyOwner
{
uniswapV2Pool = uniswapV2Pair_;
}
function setBurningDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
burningDiscount = discount;
}
// amount in is 10 ** 9 decimals
function burn(uint256 amount)
external
updateAccount(msg.sender)
{
require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
reEntrancyMutex = true;
require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE');
require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID');
require(_remainingEurosToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _euroBalances[msg.sender], 'INSUFFICIENT_EURO_BALANCE');
require(amount <= _remainingEurosToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
_burn(msg.sender, amount);
reEntrancyMutex = false;
}
function setDefaultDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDiscount = discount;
}
function setMaxDiscount(uint256 discount)
external
onlyOwner
{
_maxDiscount = discount;
}
function setDefaultDailyBonusDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDailyBonusDiscount = discount;
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
// action of claiming funds
function claimDividends(address account) public updateAccount(account) returns (uint256) {
uint256 owing = dividendsOwing(account);
return owing;
}
function setMinimumBonusThreshold(uint256 minimum)
external
onlyOwner
{
require(minimum >= 0, 'POSITIVE_MINIMUM');
require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH');
minimumBonusThreshold = minimum;
}
function syncUniswapV2()
external
{
uniswapV2Pool.call(abi.encodeWithSignature('sync()'));
}
/**
* @dev Notifies Euros contract about a new rebase cycle.
* @param supplyDelta The number of new euro tokens to add into circulation via expansion.
* @return The total number of euros after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
whenRebaseNotPaused
returns (uint256)
{
reEntrancyRebaseMutex = true;
if (supplyDelta == 0) {
if (_remainingEurosToBeBurned > minimumBonusThreshold) {
burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ?
_maxDiscount : burningDiscount.add(defaultDailyBonusDiscount);
} else {
burningDiscount = defaultDiscount;
}
emit LogRebase(epoch, _totalSupply);
}
if (supplyDelta < 0) {
uint256 eurosToBurn = uint256(supplyDelta.abs());
if (eurosToBurn > _totalSupply.div(10)) { // maximum contraction is 10% of the total EUR Supply
eurosToBurn = _totalSupply.div(10);
}
if (eurosToBurn.add(_remainingEurosToBeBurned) > _totalSupply) {
eurosToBurn = _totalSupply.sub(_remainingEurosToBeBurned);
}
if (_remainingEurosToBeBurned > minimumBonusThreshold) {
burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ?
_maxDiscount : burningDiscount.add(defaultDailyBonusDiscount);
} else {
burningDiscount = defaultDiscount; // default 1%
}
_remainingEurosToBeBurned = _remainingEurosToBeBurned.add(eurosToBurn);
emit LogContraction(epoch, eurosToBurn);
} else {
disburse(uint256(supplyDelta));
uniswapV2Pool.call(abi.encodeWithSignature('sync()'));
emit LogRebase(epoch, _totalSupply);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
}
reEntrancyRebaseMutex = false;
return _totalSupply;
}
function initialize(address owner_, address seigniorageAddress)
public
initializer
{
ERC20Detailed.initialize("Euros", "EUR", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
_totalSupply = INITIAL_EURO_SUPPLY;
sharesAddress = seigniorageAddress;
Shares = ISeigniorageShares(seigniorageAddress);
_euroBalances[owner_] = _totalSupply;
_maxDiscount = 50 * 10 ** 9; // 50%
defaultDiscount = 1 * 10 ** 9; // 1%
burningDiscount = defaultDiscount;
defaultDailyBonusDiscount = 1 * 10 ** 9; // 1%
minimumBonusThreshold = 100 * 10 ** 9; // 100 euros is the minimum threshold. Anything above warrants increased discount
emit Transfer(address(0x0), owner_, _totalSupply);
}
function dividendsOwing(address account) public view returns (uint256) {
if (_totalDividendPoints > Shares.lastDividendPoints(account)) {
uint256 newDividendPoints = _totalDividendPoints.sub(Shares.lastDividendPoints(account));
uint256 sharesBalance = Shares.externalRawBalanceOf(account);
return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER);
} else {
return 0;
}
}
// auto claim modifier
// if user is owned, we pay out immedietly
// if user is not owned, we prevent them from claiming until the next rebase
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if (owing > 0) {
_unclaimedDividends = _unclaimedDividends.sub(owing);
if (!deleteWhitelist[account]) {
_euroBalances[account] += owing;
emit Transfer(address(0), account, owing);
}
}
if (deleteWhitelist[account]) {
_delete(account);
}
Shares.setDividendPoints(account, _totalDividendPoints);
emit LogClaim(account, owing);
_;
}
/**
* @return The total number of euros.
*/
function totalSupply()
external
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _euroBalances[who].add(dividendsOwing(who));
}
function getRemainingEurosToBeBurned()
public
view
returns (uint256)
{
return _remainingEurosToBeBurned;
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
if (_euroBalances[msg.sender] > 0 && !deleteWhitelist[to]) {
_euroBalances[msg.sender] = _euroBalances[msg.sender].sub(value);
_euroBalances[to] = _euroBalances[to].add(value);
emit Transfer(msg.sender, to, value);
}
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedEuros[owner_][spender];
}
function getDeleteWhitelist(address who_)
public
view
returns (bool)
{
return deleteWhitelist[who_];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
updateAccount(from)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
if (_euroBalances[from] > 0 && !deleteWhitelist[to]) {
_allowedEuros[from][msg.sender] = _allowedEuros[from][msg.sender].sub(value);
_euroBalances[from] = _euroBalances[from].sub(value);
_euroBalances[to] = _euroBalances[to].add(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. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
validRecipient(spender)
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedEuros[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedEuros[msg.sender][spender] =
_allowedEuros[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedEuros[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
updateAccount(spender)
updateAccount(msg.sender)
returns (bool)
{
uint256 oldValue = _allowedEuros[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedEuros[msg.sender][spender] = 0;
} else {
_allowedEuros[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedEuros[msg.sender][spender]);
return true;
}
function consultBurn(uint256 amount)
public
returns (uint256)
{
require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE');
require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID');
require(_remainingEurosToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _euroBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_EURO_BALANCE');
require(amount <= _remainingEurosToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
uint256 euroPerShare = EuroPolicy.getEuroSharePrice(); // 1 share = x euros
euroPerShare = euroPerShare.sub(euroPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9
uint256 sharesToMint = amount.mul(10 ** 9).div(euroPerShare); // 10^9
return sharesToMint;
}
function unclaimedDividends()
public
view
returns (uint256)
{
return _unclaimedDividends;
}
function totalDividendPoints()
public
view
returns (uint256)
{
return _totalDividendPoints;
}
function disburse(uint256 amount) internal returns (bool) {
_totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(Shares.externalTotalSupply()));
_totalSupply = _totalSupply.add(amount);
_unclaimedDividends = _unclaimedDividends.add(amount);
return true;
}
function _delete(address account)
internal
{
uint256 amount = _euroBalances[account];
if (amount > 0) {
// master switch
if (euroDeletion) {
_totalSupply = _totalSupply.sub(amount);
_euroBalances[account] = _euroBalances[account].sub(amount);
}
emit LogDeletion(account, amount);
emit Transfer(account, address(0), amount);
}
}
function _burn(address account, uint256 amount)
internal
{
_totalSupply = _totalSupply.sub(amount);
_euroBalances[account] = _euroBalances[account].sub(amount);
uint256 euroPerShare = EuroPolicy.getEuroSharePrice(); // 1 share = x euros
euroPerShare = euroPerShare.sub(euroPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9
uint256 sharesToMint = amount.mul(10 ** 9).div(euroPerShare); // 10^9
_remainingEurosToBeBurned = _remainingEurosToBeBurned.sub(amount);
Shares.mintShares(account, sharesToMint);
emit Transfer(account, address(0), amount);
emit LogBurn(account, amount);
}
}
// File: contracts/interface/IReserve.sol
pragma solidity >=0.4.24;
interface IReserve {
function buyReserveAndTransfer(uint256 mintAmount) external;
}
// File: contracts/euro/eurosPolicy.sol
pragma solidity >=0.4.24;
/*
* Euro Policy
*/
interface IDecentralizedOracle {
function update() external;
function consult(address token, uint amountIn) external view returns (uint amountOut);
}
contract EurosPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
Euros public euros;
// Provides the current CPI, as an 18 decimal fixed point number.
IDecentralizedOracle public sharesPerEuroOracle;
IDecentralizedOracle public ethPerEuroOracle;
IDecentralizedOracle public ethPerEurocOracle;
uint256 public deviationThreshold;
uint256 public rebaseLag;
uint256 private cpi;
uint256 public minRebaseTimeIntervalSec;
uint256 public lastRebaseTimestampSec;
uint256 public rebaseWindowOffsetSec;
uint256 public rebaseWindowLengthSec;
uint256 public epoch;
address public WETH_ADDRESS;
address public SHARE_ADDRESS;
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
address public orchestrator;
bool private initializedOracle;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator);
_;
}
uint256 public minimumEuroCirculation;
uint256 public constant MAX_SLIPPAGE_PARAM = 1180339 * 10**2; // max ~20% market impact
uint256 public constant MAX_MINT_PERC_PARAM = 25 * 10**7; // max 25% of rebase can go to treasury
uint256 public rebaseMintPerc;
uint256 public maxSlippageFactor;
address public treasury;
address public public_goods;
uint256 public public_goods_perc;
event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor);
event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc);
function getEuroSharePrice() external view returns (uint256) {
uint256 sharePrice = sharesPerEuroOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals
return sharePrice;
}
function initializeReserve(address treasury_)
external
onlyOwner
returns (bool)
{
maxSlippageFactor = 5409258 * 10; // 5.4% = 10 ^ 9 base
rebaseMintPerc = 10 ** 8; // 10%
treasury = treasury_;
return true;
}
function mint(uint256 amount_) external onlyOwner {
euros.mintCash(msg.sender, amount_);
}
function rebase() external onlyOrchestrator {
require(inRebaseWindow(), "OUTISDE_REBASE");
require(initializedOracle == true, 'ORACLE_NOT_INITIALIZED');
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "MIN_TIME_NOT_MET");
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
sharesPerEuroOracle.update();
ethPerEuroOracle.update();
ethPerEurocOracle.update();
uint256 ethEurocPrice = ethPerEurocOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^18 decimals ropsten, 10^6 mainnet
uint256 ethEuroPrice = ethPerEuroOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^9 decimals
uint256 euroCoinExchangeRate = ethEurocPrice.mul(10 ** 9) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet
.div(ethEuroPrice);
uint256 sharePrice = sharesPerEuroOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals
uint256 shareExchangeRate = sharePrice.mul(euroCoinExchangeRate).div(10 ** 18); // 10^18 decimals
uint256 targetRate = cpi;
if (euroCoinExchangeRate > MAX_RATE) {
euroCoinExchangeRate = MAX_RATE;
}
// euroCoinExchangeRate & targetRate arre 10^18 decimals
int256 supplyDelta = computeSupplyDelta(euroCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals
// // Apply the Dampening factor.
// // supplyDelta = supplyDelta.mul(10 ** 9).div(rebaseLag.toInt256Safe());
uint256 algorithmicLag_ = getAlgorithmicRebaseLag(supplyDelta);
require(algorithmicLag_ > 0, "algorithmic rate must be positive");
rebaseLag = algorithmicLag_;
supplyDelta = supplyDelta.mul(10 ** 9).div(algorithmicLag_.toInt256Safe()); // v 0.0.1
// check on the expansionary side
if (supplyDelta > 0 && euros.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(euros.totalSupply())).toInt256Safe();
}
// check on the contraction side
if (supplyDelta < 0 && euros.getRemainingEurosToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(euros.getRemainingEurosToBeBurned())).toInt256Safe();
}
// set minimum floor
if (supplyDelta < 0 && euros.totalSupply().sub(euros.getRemainingEurosToBeBurned().add(uint256(supplyDelta.abs()))) < minimumEuroCirculation) {
supplyDelta = (euros.totalSupply().sub(euros.getRemainingEurosToBeBurned()).sub(minimumEuroCirculation)).toInt256Safe();
}
uint256 supplyAfterRebase;
if (supplyDelta < 0) { // contraction, we send the amount of shares to mint
uint256 eurosToBurn = uint256(supplyDelta.abs());
supplyAfterRebase = euros.rebase(epoch, (eurosToBurn).toInt256Safe().mul(-1));
} else { // expansion, we send the amount of euros to mint
supplyAfterRebase = euros.rebase(epoch, supplyDelta);
uint256 treasuryAmount = uint256(supplyDelta).mul(rebaseMintPerc).div(10 ** 9);
uint256 supplyDeltaMinusTreasury = uint256(supplyDelta).sub(treasuryAmount);
supplyAfterRebase = euros.rebase(epoch, (supplyDeltaMinusTreasury).toInt256Safe());
if (treasuryAmount > 0) {
// call reserve swap
IReserve(treasury).buyReserveAndTransfer(treasuryAmount);
}
}
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, euroCoinExchangeRate, cpi, supplyDelta, now);
}
function setOrchestrator(address orchestrator_)
external
onlyOwner
{
orchestrator = orchestrator_;
}
function setPublicGoods(address public_goods_, uint256 public_goods_perc_)
external
onlyOwner
{
public_goods = public_goods_;
public_goods_perc = public_goods_perc_;
}
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyOwner
{
deviationThreshold = deviationThreshold_;
}
function setCpi(uint256 cpi_)
external
onlyOwner
{
require(cpi_ > 0);
cpi = cpi_;
}
function getCpi()
external
view
returns (uint256)
{
return cpi;
}
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
function initializeOracles(
address sharesPerEuroOracleAddress,
address ethPerEuroOracleAddress,
address ethPerEurocOracleAddress
) external onlyOwner {
require(initializedOracle == false, 'ALREADY_INITIALIZED_ORACLE');
sharesPerEuroOracle = IDecentralizedOracle(sharesPerEuroOracleAddress);
ethPerEuroOracle = IDecentralizedOracle(ethPerEuroOracleAddress);
ethPerEurocOracle = IDecentralizedOracle(ethPerEurocOracleAddress);
initializedOracle = true;
}
function changeOracles(
address sharesPerEuroOracleAddress,
address ethPerEuroOracleAddress,
address ethPerEurocOracleAddress
) external onlyOwner {
sharesPerEuroOracle = IDecentralizedOracle(sharesPerEuroOracleAddress);
ethPerEuroOracle = IDecentralizedOracle(ethPerEuroOracleAddress);
ethPerEurocOracle = IDecentralizedOracle(ethPerEurocOracleAddress);
}
function setWethAddress(address wethAddress)
external
onlyOwner
{
WETH_ADDRESS = wethAddress;
}
function setShareAddress(address shareAddress)
external
onlyOwner
{
SHARE_ADDRESS = shareAddress;
}
function setMinimumEuroCirculation(uint256 minimumEuroCirculation_)
external
onlyOwner
{
minimumEuroCirculation = minimumEuroCirculation_;
}
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyOwner
{
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
function initialize(address owner_, Euros euros_)
public
initializer
{
Ownable.initialize(owner_);
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 50 * 10 ** 9;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug)
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
cpi = 1 * 10 ** 18;
epoch = 0;
minimumEuroCirculation = 1000000 * 10 ** 9; // 1M minimum euro circulation
euros = euros_;
}
// takes current marketcap of EURO and calculates the algorithmic rebase lag
// returns 10 ** 9 rebase lag factor
function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) {
if (euros.totalSupply() >= 30000000 * 10 ** 9) {
return 30 * 10 ** 9;
} else {
require(euros.totalSupply() > 1000000 * 10 ** 9, "MINIMUM EURO SUPPLY NOT MET");
if (supplyDelta < 0) {
uint256 eurosToBurn = uint256(supplyDelta.abs()); // 1.238453076e15
return uint256(100 * 10 ** 9).sub((euros.totalSupply().sub(1000000 * 10 ** 9)).div(500000));
} else {
return uint256(29).mul(euros.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9);
}
}
}
function setMaxSlippageFactor(uint256 maxSlippageFactor_)
public
onlyOwner
{
require(maxSlippageFactor_ < MAX_SLIPPAGE_PARAM);
uint256 oldSlippageFactor = maxSlippageFactor;
maxSlippageFactor = maxSlippageFactor_;
emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_);
}
function setRebaseMintPerc(uint256 rebaseMintPerc_)
public
onlyOwner
{
require(rebaseMintPerc_ < MAX_MINT_PERC_PARAM);
uint256 oldPerc = rebaseMintPerc;
rebaseMintPerc = rebaseMintPerc_;
emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_);
}
function inRebaseWindow() public view returns (bool) {
return (
now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))
);
}
function computeSupplyDelta(uint256 rate, uint256 targetRate)
private
view
returns (int256)
{
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return euros.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
} | Transfer tokens to a specified address. to The address to transfer to. value The amount to be transferred. return True on success, false otherwise./ | {
require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
function totalSupply()
external
view
returns (uint256)
}
function balanceOf(address who)
external
view
returns (uint256)
}
function getRemainingEurosToBeBurned()
public
view
returns (uint256)
}
function transfer(address to, uint256 value)
external
validRecipient(to)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
if (_euroBalances[msg.sender] > 0 && !deleteWhitelist[to]) {
_euroBalances[msg.sender] = _euroBalances[msg.sender].sub(value);
_euroBalances[to] = _euroBalances[to].add(value);
emit Transfer(msg.sender, to, value);
}
return true;
}
| 6,605,010 |
pragma solidity ^0.4.24;
import "./DestructibleMiniMeTokenFactory.sol";
import "./Ownable.sol";
/*
Copyright 2018, Will Harborne @ Ethfinex
*/
/// @title ProposalManager Contract
/// @author Will Harborne @ Ethfinex
contract TokenListingManagerAdvanced is Ownable {
address public constant NECTAR_TOKEN = 0xCc80C051057B774cD75067Dc48f8987C4Eb97A5e;
address public constant TOKEN_FACTORY = 0x6EB97237B8bc26E8057793200207bB0a2A83C347;
uint public constant MAX_CANDIDATES = 50;
struct TokenProposal {
uint startBlock;
uint startTime;
uint duration;
address votingToken;
// criteria values
// 0. only first one win the vote;
// 1. top N (number in extraData) win the vote;
// 2. All over N (number in extra data) votes win the vote;
uint criteria;
uint extraData;
}
struct Delegate {
address user;
bytes32 storageHash;
bool exists;
}
TokenProposal[] public tokenBatches;
Delegate[] public allDelegates;
mapping(address => uint) addressToDelegate;
uint[] public yesVotes;
address[] public consideredTokens;
DestructibleMiniMeTokenFactory public tokenFactory;
address public nectarToken;
mapping(address => bool) public admins;
mapping(address => bool) public isWinner;
mapping(address => bool) public tokenExists;
mapping(address => uint) public lastVote;
mapping(address => address[]) public myVotes;
mapping(address => address) public myDelegate;
mapping(address => bool) public isDelegate;
mapping(uint => mapping(address => uint256)) public votesSpentThisRound;
modifier onlyAdmins() {
require(isAdmin(msg.sender));
_;
}
constructor(address _tokenFactory, address _nectarToken) public {
tokenFactory = DestructibleMiniMeTokenFactory(_tokenFactory);
nectarToken = _nectarToken;
admins[msg.sender] = true;
isDelegate[address(0)] = true;
}
/// @notice Admins are able to approve proposal that someone submitted
/// @param _tokens the list of tokens in consideration during this period
/// @param _duration number of days for voting
/// @param _criteria number that determines how winner is selected
/// @param _extraData extra data for criteria parameter
/// @param _previousWinners addresses that won previous proposal
function startTokenVotes(address[] _tokens, uint _duration, uint _criteria, uint _extraData, address[] _previousWinners) public onlyAdmins {
require(_tokens.length <= MAX_CANDIDATES);
for (uint i=0; i < _previousWinners.length; i++) {
isWinner[_previousWinners[i]] = true;
}
if (_criteria == 1) {
// in other case all tokens would be winners
require(_extraData < consideredTokens.length);
}
uint _proposalId = tokenBatches.length;
if (_proposalId > 0) {
TokenProposal memory op = tokenBatches[_proposalId - 1];
DestructibleMiniMeToken(op.votingToken).recycle();
}
tokenBatches.length++;
TokenProposal storage p = tokenBatches[_proposalId];
p.duration = _duration * (1 days);
for (i = 0; i < _tokens.length; i++) {
require(!tokenExists[_tokens[i]]);
consideredTokens.push(_tokens[i]);
yesVotes.push(0);
lastVote[_tokens[i]] = _proposalId;
tokenExists[_tokens[i]] = true;
}
p.votingToken = tokenFactory.createDestructibleCloneToken(
nectarToken,
getBlockNumber(),
appendUintToString("EfxTokenVotes-", _proposalId),
MiniMeToken(nectarToken).decimals(),
appendUintToString("EVT-", _proposalId),
true);
p.startTime = now;
p.startBlock = getBlockNumber();
p.criteria = _criteria;
p.extraData = _extraData;
emit NewTokens(_proposalId);
}
/// @notice Vote for specific token with yes
/// @param _tokenIndex is the position from 0-9 in the token array of the chosen token
/// @param _amount number of votes you give for this token
function vote(uint _tokenIndex, uint _amount) public {
require(myDelegate[msg.sender] == address(0));
require(!isWinner[consideredTokens[_tokenIndex]]);
// voting only on the most recent set of proposed tokens
require(tokenBatches.length > 0);
uint _proposalId = tokenBatches.length - 1;
require(isActive(_proposalId));
TokenProposal memory p = tokenBatches[_proposalId];
if (lastVote[consideredTokens[_tokenIndex]] < _proposalId) {
// if voting for this token for first time in current proposal, we need to deduce votes
// we deduce number of yes votes for diff of current proposal and lastVote time multiplied by 2
yesVotes[_tokenIndex] /= 2*(_proposalId - lastVote[consideredTokens[_tokenIndex]]);
lastVote[consideredTokens[_tokenIndex]] = _proposalId;
}
uint balance = DestructibleMiniMeToken(p.votingToken).balanceOf(msg.sender);
// user is able to have someone in myVotes if he unregistered and some people didn't undelegated him after that
if (isDelegate[msg.sender]) {
for (uint i=0; i < myVotes[msg.sender].length; i++) {
address user = myVotes[msg.sender][i];
balance += DestructibleMiniMeToken(p.votingToken).balanceOf(user);
}
}
require(_amount <= balance);
require(votesSpentThisRound[_proposalId][msg.sender] + _amount <= balance);
yesVotes[_tokenIndex] += _amount;
// set the info that the user voted in this round
votesSpentThisRound[_proposalId][msg.sender] += _amount;
emit Vote(_proposalId, msg.sender, consideredTokens[_tokenIndex], _amount);
}
function unregisterAsDelegate() public {
require(isDelegate[msg.sender]);
address lastDelegate = allDelegates[allDelegates.length - 1].user;
uint currDelegatePos = addressToDelegate[msg.sender];
// set last delegate to new pos
addressToDelegate[lastDelegate] = currDelegatePos;
allDelegates[currDelegatePos] = allDelegates[allDelegates.length - 1];
// delete this delegate
delete allDelegates[allDelegates.length - 1];
allDelegates.length--;
// set bool to false
isDelegate[msg.sender] = false;
}
function registerAsDelegate(bytes32 _storageHash) public {
// can't register as delegate if already gave vote
require(!gaveVote(msg.sender));
// can't register as delegate if you have delegate (undelegate first)
require(myDelegate[msg.sender] == address(0));
// can't call this method if you are already delegate
require(!isDelegate[msg.sender]);
isDelegate[msg.sender] = true;
allDelegates.push(Delegate({
user: msg.sender,
storageHash: _storageHash,
exists: true
}));
addressToDelegate[msg.sender] = allDelegates.length-1;
}
function undelegateVote() public {
// can't undelegate if I already gave vote in this round
require(!gaveVote(msg.sender));
// I must have delegate if I want to undelegate
require(myDelegate[msg.sender] != address(0));
address delegate = myDelegate[msg.sender];
for (uint i=0; i < myVotes[delegate].length; i++) {
if (myVotes[delegate][i] == msg.sender) {
myVotes[delegate][i] = myVotes[delegate][myVotes[delegate].length-1];
delete myVotes[delegate][myVotes[delegate].length-1];
myVotes[delegate].length--;
break;
}
}
myDelegate[msg.sender] = address(0);
}
/// @notice Delegate vote to other address
/// @param _to address who will be able to vote instead of you
function delegateVote(address _to) public {
// not possible to delegate if I already voted
require(!gaveVote(msg.sender));
// can't set delegate if I am delegate
require(!isDelegate[msg.sender]);
// I can only set delegate to someone who is registered delegate
require(isDelegate[_to]);
// I can't have delegate if I'm setting one (call undelegate first)
require(myDelegate[msg.sender] == address(0));
myDelegate[msg.sender] = _to;
myVotes[_to].push(msg.sender);
}
function delegateCount() public view returns(uint) {
return allDelegates.length;
}
function getWinners() public view returns(address[] winners) {
require(tokenBatches.length > 0);
uint _proposalId = tokenBatches.length - 1;
TokenProposal memory p = tokenBatches[_proposalId];
// there is only one winner in criteria 0
if (p.criteria == 0) {
winners = new address[](1);
uint max = 0;
for (uint i=0; i < consideredTokens.length; i++) {
if (isWinner[consideredTokens[i]]) {
continue;
}
if (isWinner[consideredTokens[max]]) {
max = i;
}
if (getCurrentVotes(i) > getCurrentVotes(max)) {
max = i;
}
}
winners[0] = consideredTokens[max];
}
// there is N winners in criteria 1
if (p.criteria == 1) {
uint count = 0;
uint[] memory indexesWithMostVotes = new uint[](p.extraData);
winners = new address[](p.extraData);
// for each token we check if he has more votes than last one,
// if it has we put it in array and always keep array sorted
for (i = 0; i < consideredTokens.length; i++) {
if (isWinner[consideredTokens[i]]) {
continue;
}
if (count < p.extraData) {
indexesWithMostVotes[count] = i;
count++;
continue;
}
// so we just do it once, sort all in descending order
if (count == p.extraData) {
for (j = 0; j < indexesWithMostVotes.length; j++) {
for (uint k = j+1; k < indexesWithMostVotes.length; k++) {
if (getCurrentVotes(indexesWithMostVotes[j]) < getCurrentVotes(indexesWithMostVotes[k])) {
uint help = indexesWithMostVotes[j];
indexesWithMostVotes[j] = indexesWithMostVotes[k];
indexesWithMostVotes[k] = help;
}
}
}
}
uint last = p.extraData - 1;
if (getCurrentVotes(i) > getCurrentVotes(indexesWithMostVotes[last])) {
indexesWithMostVotes[last] = i;
for (uint j=last; j > 0; j--) {
if (getCurrentVotes(indexesWithMostVotes[j]) > getCurrentVotes(indexesWithMostVotes[j-1])) {
help = indexesWithMostVotes[j];
indexesWithMostVotes[j] = indexesWithMostVotes[j-1];
indexesWithMostVotes[j-1] = help;
}
}
}
}
for (i = 0; i < p.extraData; i++) {
winners[i] = consideredTokens[indexesWithMostVotes[i]];
}
}
// everybody who has over N votes are winners in criteria 2
if (p.criteria == 2) {
uint numOfTokens = 0;
for (i = 0; i < consideredTokens.length; i++) {
if (isWinner[consideredTokens[i]]) {
continue;
}
if (getCurrentVotes(i) > p.extraData) {
numOfTokens++;
}
}
winners = new address[](numOfTokens);
count = 0;
for (i = 0; i < consideredTokens.length; i++) {
if (isWinner[consideredTokens[i]]) {
continue;
}
if (getCurrentVotes(i) > p.extraData) {
winners[count] = consideredTokens[i];
count++;
}
}
}
}
/// @notice Get number of proposals so you can know which is the last one
function numberOfProposals() public view returns(uint) {
return tokenBatches.length;
}
/// @notice Any admin is able to add new admin
/// @param _newAdmin Address of new admin
function addAdmin(address _newAdmin) public onlyAdmins {
admins[_newAdmin] = true;
}
/// @notice Only owner is able to remove admin
/// @param _admin Address of current admin
function removeAdmin(address _admin) public onlyOwner {
admins[_admin] = false;
}
/// @notice Get data about specific proposal
/// @param _proposalId Id of proposal
function proposal(uint _proposalId) public view returns(
uint _startBlock,
uint _startTime,
uint _duration,
bool _active,
bool _finalized,
uint[] _votes,
address[] _tokens,
address _votingToken,
bool _hasBalance
) {
require(_proposalId < tokenBatches.length);
TokenProposal memory p = tokenBatches[_proposalId];
_startBlock = p.startBlock;
_startTime = p.startTime;
_duration = p.duration;
_finalized = (_startTime+_duration < now);
_active = isActive(_proposalId);
_votes = getVotes();
_tokens = getConsideredTokens();
_votingToken = p.votingToken;
_hasBalance = (p.votingToken == 0x0) ? false : (DestructibleMiniMeToken(p.votingToken).balanceOf(msg.sender) > 0);
}
function getConsideredTokens() public view returns(address[] tokens) {
tokens = new address[](consideredTokens.length);
for (uint i = 0; i < consideredTokens.length; i++) {
if (!isWinner[consideredTokens[i]]) {
tokens[i] = consideredTokens[i];
} else {
tokens[i] = address(0);
}
}
}
function getVotes() public view returns(uint[] votes) {
votes = new uint[](consideredTokens.length);
for (uint i = 0; i < consideredTokens.length; i++) {
votes[i] = getCurrentVotes(i);
}
}
function getCurrentVotes(uint index) public view returns(uint) {
require(tokenBatches.length > 0);
uint _proposalId = tokenBatches.length - 1;
uint vote = yesVotes[index];
if (_proposalId > lastVote[consideredTokens[index]]) {
vote = yesVotes[index] / (2 * (_proposalId - lastVote[consideredTokens[index]]));
}
return vote;
}
function isAdmin(address _admin) public view returns(bool) {
return admins[_admin];
}
function proxyPayment(address ) public payable returns(bool) {
return false;
}
// only users that didn't gave vote in current round can transfer tokens
function onTransfer(address _from, address _to, uint _amount) public view returns(bool) {
return !gaveVote(_from);
}
function onApprove(address, address, uint ) public pure returns(bool) {
return true;
}
function gaveVote(address _user) public view returns(bool) {
if (tokenBatches.length == 0) return false;
uint _proposalId = tokenBatches.length - 1;
if (votesSpentThisRound[_proposalId][myDelegate[_user]] + votesSpentThisRound[_proposalId][_user] > 0 ) {
return true;
} else {
return false;
}
}
function getBlockNumber() internal constant returns (uint) {
return block.number;
}
function isActive(uint id) internal view returns (bool) {
TokenProposal memory p = tokenBatches[id];
bool _finalized = (p.startTime + p.duration < now);
return !_finalized && (p.startBlock < getBlockNumber());
}
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
if (v == 0) {
reversed[i++] = byte(48);
} else {
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
event Vote(uint indexed idProposal, address indexed _voter, address chosenToken, uint amount);
event NewTokens(uint indexed idProposal);
}
| Get data about specific proposal _proposalId Id of proposal | function proposal(uint _proposalId) public view returns(
uint _startBlock,
uint _startTime,
uint _duration,
bool _active,
bool _finalized,
uint[] _votes,
address[] _tokens,
address _votingToken,
bool _hasBalance
) {
require(_proposalId < tokenBatches.length);
TokenProposal memory p = tokenBatches[_proposalId];
_startBlock = p.startBlock;
_startTime = p.startTime;
_duration = p.duration;
_finalized = (_startTime+_duration < now);
_active = isActive(_proposalId);
_votes = getVotes();
_tokens = getConsideredTokens();
_votingToken = p.votingToken;
_hasBalance = (p.votingToken == 0x0) ? false : (DestructibleMiniMeToken(p.votingToken).balanceOf(msg.sender) > 0);
}
| 5,475,493 |
./full_match/42220/0x65b898d61a08De8F5cB2F568A18970b010e06829/sources/contracts/pools/InkRewardPool.sol | View function to see pending INKs on frontend. | function pendingShare(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accInkPerShare = pool.accInkPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _inkReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accInkPerShare = accInkPerShare.add(_inkReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accInkPerShare).div(1e18).sub(user.rewardDebt);
}
| 16,356,947 |
./partial_match/288/0xeBb58F932729aBB31d6fd7200088ba43A1631595/sources/contracts/Ola/Core/LendingNetwork/versions/0.01/ODelegatorFactoryV0_01.sol | Calculate the initial exchange rate mantissa (0.02 scaled by underlyingDecimals + 10) Sanity 0.02 (e10) | function calculateInitialExchangeRateMantissaForCERC20(uint8 underlyingDecimals) internal pure returns (uint) {
require(underlyingDecimals <= 30, "Too big decimals");
uint baseInitialExchangeRateScaledBy10 = 200000000;
uint initialExchangeRateMantissa = baseInitialExchangeRateScaledBy10 * (10 ** underlyingDecimals);
return initialExchangeRateMantissa;
}
| 16,906,219 |
./partial_match/1/0x986A4010D6dF5754f66F72764487070615CBDE9A/sources/contracts/ERC1155MintRange.sol | Implement: Return initial token balance for address. This function MUST be pure: Always return the same values for a given input. Returns current token balance of account calculates and returns initial dynamic balance if minted via _mintRange and not yet initialized. | function initialBalanceOf(
address account,
uint tokenId
) internal view virtual returns (uint);
function balanceOf(
address account,
uint id
) public view virtual override returns (uint) {
require(account != address(0), "ERC1155: not a valid owner");
if (
_maybeInitialHolder(account) &&
!isBalanceInitialized[account][id] &&
!isManualMint[id] &&
_inRange(id)
) {
return initialBalanceOf(account, id);
}
return _balances[id][account];
}
| 9,362,297 |
./full_match/421613/0x105450Ba8a99142f186f089c66c367AD0150cb89/sources/contracts/MafiaNuts.sol | weekly mint for trading competition | Can be called every week to the new winner. | function mintNutTo(address _winner) external onlyOwner {
require(totalSupply() < MAX_SUPPLY, "Mint would exceed max supply");
unchecked {
TRADING_COMPETITION_SUPPLY--;
}
_mint(_winner, 1);
}
| 11,571,312 |
pragma solidity ^0.4.18;
import './HuhulaToken.sol';
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
/**
Huhula crowdsale
*/
contract HuhulaSale is Ownable, TimedCrowdsale(block.timestamp + 1, block.timestamp + 1 + 10368000), Pausable {
using SafeMath for uint256;
//**********************************************************************************************
// ------------------------------ Customize Smart Contract -------------------------------------
uint32 public buyBackRate = 1034; // in ETH with 6 decimal places per token, initially 0.001034
//**********************************************************************************************
uint256 public minLotSize = 5 ether;
constructor() public
Crowdsale(23356, 0xa4aA1C90f02265d189a96207Be92597fFEaD54D2, new HuhulaToken("Huhula spot","HUHU") ) {
}
function calcTokens(uint256 weiAmount) internal view returns(uint256) {
// calculate token amount to be sent to buyer
uint256 tokens = weiAmount.mul(rate).mul(1000000).div(1 ether).div(100);
uint256 tokensLeft = HuhulaToken(token).cap().sub(token.totalSupply());
if ( tokensLeft < tokens ) {
tokens = tokensLeft;
}
return tokens;
}
// Events
event SpenderApproved(address indexed to, uint256 tokens);
event GrantTokens(address indexed to, uint256 tokens);
event RewardTokens(address indexed to, uint256 tokens);
event RateChange(uint256 rate);
/**
* @dev Sets HUHU to Ether rate. Will be called multiple times durign the crowdsale to adjsut the rate
* since HUHU cost is fixed in USD, but USD/ETH rate is changing
* @param paramRate defines HUHU/ETH rate: 1 ETH = paramRate HUHUs
*/
function setRate(uint256 paramRate) public onlyOwner {
require(paramRate >= 1);
rate = paramRate;
emit RateChange(paramRate);
}
function setMinLotSize(uint256 paramLot) public onlyOwner {
require(paramLot >= 1 finney);
minLotSize = paramLot;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public whenNotPaused payable {
require(beneficiary != address(0));
require(block.timestamp <= closingTime);
uint256 weiAmount = msg.value;
require(weiAmount >= minLotSize);
// calculate token amount to be created
uint256 tokens = calcTokens(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
if ( HuhulaToken(token).mint(beneficiary, tokens) ) {
emit TokenPurchase(address(0x0), beneficiary, weiAmount, tokens);
forwardFunds();
}
}
/**
Function to grant some tokens to early testers before or during crowdsale
*/
function grantTokens(address beneficiary,uint256 tokens) public onlyOwner {
require(beneficiary != address(0));
require(block.timestamp <= closingTime);
if ( HuhulaToken(token).mint(beneficiary, tokens) ) {
emit GrantTokens(beneficiary, tokens);
}
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
/**
* @dev Allows to resume crowdsale
*/
function resume(uint256 _hours) public onlyOwner {
require(_hours <= 744); // shorter than longest month, i.e. max one month
require(_hours > 0);
closingTime = closingTime.add(_hours.mul(3600)); // convert to seconds and add to closingTimea
if ( paused )
unpause();
}
/**
* @dev Sets the wallet to forward ETH collected funds
*/
function setWallet(address paramWallet) public onlyOwner {
require(paramWallet != 0x0);
wallet = paramWallet;
}
/**
* allows to approve the sale if goal in dollars reached, or other admin reasons
*/
function approve() public onlyOwner {
conclude();
}
/**
* @dev Finalizes the crowdsale, mint and transfer all ramaining tokens to owner
*/
function conclude() internal {
if (token.totalSupply() < HuhulaToken(token).cap()) {
uint tokens = HuhulaToken(token).cap().sub(token.totalSupply());
if ( ! HuhulaToken(token).mint(owner, tokens) ) {
revert();
}
}
HuhulaToken(token).finishMinting();
// take onwership over HuhuToken contract
HuhulaToken(token).transferOwnership(owner);
}
event BuyBackRateChange(uint32 rate);
event BuyBackTransfer(address indexed from, address indexed to, uint256 value);
event ReturnBuyBack(address indexed from, address indexed to, uint256 value);
function setBuyBackRate(uint32 paramRate) public onlyOwner {
require(paramRate >= 1);
buyBackRate = paramRate;
emit BuyBackRateChange(buyBackRate);
}
/**
* Accumulate some Ether on address of this contract to do buyback
*/
function fundForBuyBack() payable public onlyOwner returns(bool success) {
return true;
}
/**
* during buyBack tokens returned from given address and corresponding USD converted to ETH transferred back to holder
*/
function buyBack(address _tokenHolder, uint256 _tokens) public onlyOwner {
HuhulaToken(token).huhulaReturnToOwner(_tokenHolder, _tokens);
uint256 buyBackWei = _tokens.mul(buyBackRate).mul(10**6);
if ( _tokenHolder.send(buyBackWei) ) {
emit BuyBackTransfer(address(this), _tokenHolder, buyBackWei);
} else {
revert();
}
}
/**
* during buyBack return funds from smart contract account to funds account
*/
function returnBuyBackFunds() public onlyOwner {
uint256 weiToReturn = address(this).balance;
if ( wallet.send(weiToReturn) ) {
emit ReturnBuyBack(this, wallet, weiToReturn);
} else {
revert();
}
}
}
| during buyBack return funds from smart contract account to funds account/ | function returnBuyBackFunds() public onlyOwner {
uint256 weiToReturn = address(this).balance;
if ( wallet.send(weiToReturn) ) {
emit ReturnBuyBack(this, wallet, weiToReturn);
revert();
}
}
| 7,277,485 |
./partial_match/1/0xAD3339099ae87f1ad6e984872B95E7be24b813A7/sources/contracts/pools/PoolCollectionWithdrawal.sol | returns `p`, `q`, `r`, `s`, `t`, `u` and `v` according to the current state: +-------------------+-----------------------------------------------------------+ | `e > (b+c)/(1-n)` | bootstrap deficit or default deficit or arbitrage deficit | +-------------------+-----------------------------------------------------------+ | `e < (b+c)` | bootstrap surplus or default surplus or arbitrage surplus | +-------------------+-----------------------------------------------------------+ | otherwise | bootstrap surplus or default surplus | +-------------------+-----------------------------------------------------------+/ | function calculateWithdrawalAmounts(
) internal pure returns (Output memory output) {
if (
a > type(uint128).max ||
b > type(uint128).max ||
c > type(uint128).max ||
e > type(uint128).max ||
w > type(uint128).max ||
m > M ||
n > M ||
x > e
) {
revert PoolCollectionWithdrawalInputInvalid();
}
uint256 y = (x * (M - n)) / M;
if ((e * (M - n)) / M > b + c) {
uint256 f = (e * (M - n)) / M - (b + c);
uint256 g = e - (b + c);
if (isStable(b, c, e, x) && affordableDeficit(b, e, f, g, m, n, x)) {
output = arbitrageDeficit(a, b, e, f, m, x, y);
output = defaultDeficit(a, b, c, e, y);
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
output.s = (y * c) / e;
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
}
uint256 f = MathEx.subMax0(b + c, e);
if (f > 0 && isStable(b, c, e, x) && affordableSurplus(b, e, f, m, n, x)) {
output = arbitrageSurplus(a, b, e, f, m, n, x, y);
output = defaultSurplus(a, b, c, y);
output.s = y;
}
}
output.v = x - y;
}
| 15,613,808 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
// ============ External Imports ============
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IZoraAuctionHouse} from "../external/interfaces/IZoraAuctionHouse.sol";
// ============ Internal Imports ============
import {IMarketWrapper} from "./IMarketWrapper.sol";
/**
* @title ZoraMarketWrapper
* @author Anna Carroll
* @notice MarketWrapper contract implementing IMarketWrapper interface
* according to the logic of Zora's Auction Houses
* Original Zora Auction House code: https://github.com/ourzora/auction-house/blob/main/contracts/AuctionHouse.sol
*/
contract ZoraMarketWrapper is IMarketWrapper {
using SafeMath for uint256;
// ============ Internal Immutables ============
IZoraAuctionHouse internal immutable market;
uint8 internal immutable minBidIncrementPercentage;
// ======== Constructor =========
constructor(address _zoraAuctionHouse) {
market = IZoraAuctionHouse(_zoraAuctionHouse);
minBidIncrementPercentage = IZoraAuctionHouse(_zoraAuctionHouse)
.minBidIncrementPercentage();
}
// ======== External Functions =========
/**
* @notice Determine whether there is an existing auction
* for this token on the market
* @return TRUE if the auction exists
*/
function auctionExists(uint256 auctionId)
public
view
override
returns (bool)
{
// line 375 of Zora Auction House, _exists() function (not exposed publicly)
IZoraAuctionHouse.Auction memory _auction = market.auctions(auctionId);
return _auction.tokenOwner != address(0);
}
/**
* @notice Determine whether the given auctionId is
* an auction for the tokenId + nftContract
* @return TRUE if the auctionId matches the tokenId + nftContract
*/
function auctionIdMatchesToken(
uint256 auctionId,
address nftContract,
uint256 tokenId
) public view override returns (bool) {
IZoraAuctionHouse.Auction memory _auction = market.auctions(auctionId);
return
_auction.tokenId == tokenId &&
_auction.tokenContract == nftContract &&
_auction.auctionCurrency == address(0);
}
/**
* @notice Calculate the minimum next bid for this auction
* @return minimum bid amount
*/
function getMinimumBid(uint256 auctionId)
external
view
override
returns (uint256)
{
// line 173 of Zora Auction House, calculation within createBid() function (calculation not exposed publicly)
IZoraAuctionHouse.Auction memory _auction = market.auctions(auctionId);
if (_auction.bidder == address(0)) {
// if there are NO bids, the minimum bid is the reserve price
return _auction.reservePrice;
} else {
// if there ARE bids, the minimum bid is the current bid plus the increment buffer
return _auction.amount.add(_auction.amount.mul(minBidIncrementPercentage).div(100));
}
}
/**
* @notice Query the current highest bidder for this auction
* @return highest bidder
*/
function getCurrentHighestBidder(uint256 auctionId)
external
view
override
returns (address)
{
// line 279 of NFTMarketReserveAuction, getMinBidAmount() function
IZoraAuctionHouse.Auction memory _auction = market.auctions(auctionId);
return _auction.bidder;
}
/**
* @notice Submit bid to Market contract
*/
function bid(uint256 auctionId, uint256 bidAmount) external override {
// line 153 of Zora Auction House, createBid() function
(bool success, bytes memory returnData) =
address(market).call{value: bidAmount}(
abi.encodeWithSignature(
"createBid(uint256,uint256)",
auctionId,
bidAmount
)
);
require(success, string(returnData));
}
/**
* @notice Determine whether the auction has been finalized
* @return TRUE if the auction has been finalized
*/
function isFinalized(uint256 auctionId)
external
view
override
returns (bool)
{
// line 302 of Zora Auction House,
// the auction is deleted at the end of the endAuction() function
// since we checked that the auction DID exist when we deployed the partyBid,
// if it no longer exists that means the auction has been finalized.
return !auctionExists(auctionId);
}
/**
* @notice Finalize the results of the auction
*/
function finalize(uint256 auctionId) external override {
// line 249 of Zora Auction House, endAuction() function
market.endAuction(auctionId);
}
}
| Query the current highest bidder for this auction return highest bidder/ line 279 of NFTMarketReserveAuction, getMinBidAmount() function | function getCurrentHighestBidder(uint256 auctionId)
external
view
override
returns (address)
{
IZoraAuctionHouse.Auction memory _auction = market.auctions(auctionId);
return _auction.bidder;
}
| 1,829,813 |
./full_match/1/0xAef3e8c8723D9c31863BE8dE54dF2668Ef7c4B89/sources/contracts/core/SoundCreatorV1.sol | @inheritdoc ISoundCreatorV1/ | function soundEditionAddress(address by, bytes32 salt) external view returns (address addr, bool exists) {
addr = Clones.predictDeterministicAddress(soundEditionImplementation, _saltedSalt(by, salt), address(this));
exists = addr.code.length > 0;
}
| 16,570,401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.