file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
pragma solidity 0.4.24;
/**
*
* This contract is used to set admin to the contract which has some additional features such as minting , burning etc
*
*/
contract Owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/* This function is used to transfer adminship to new owner
* @param _newOwner - address of new admin or owner
*/
function transferOwnership(address _newOwner) onlyOwner public {
owner = _newOwner;
}
}
/**
* This is base ERC20 Contract , basically ERC-20 defines a common list of rules for all Ethereum tokens to follow
*/
contract ERC20 {
using SafeMath for uint256;
//This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) allowed;
//This maintains list of all accounts with token lock
mapping(address => bool) public isLockedAccount;
// public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
// This notifies client about the approval done by owner to spender for a given value
event Approval(address indexed owner, address indexed spender, uint256 value);
// This notifies client about the approval done
event Transfer(address indexed from, address indexed to, uint256 value);
function ERC20(uint256 _initialSupply,string _tokenName, string _tokenSymbol) public {
totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply;
name = _tokenName;
symbol = _tokenSymbol;
}
/* This function is used to transfer tokens to a particular address
* @param _to receiver address where transfer is to be done
* @param _value value to be transferred
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(!isLockedAccount[msg.sender]); // Check if sender is not blacklisted
require(!isLockedAccount[_to]); // Check if receiver is not blacklisted
require(balanceOf[msg.sender] > 0);
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require(_value > 0);
require(balanceOf[_to] .add(_value) >= balanceOf[_to]); // Check for overflows
require(_to != msg.sender); // Check if sender and receiver is not same
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract value from sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the value to the receiver
emit Transfer(msg.sender, _to, _value); // Notify all clients about the transfer events
return true;
}
/* 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
* @param _from address from which amount is to be transferred
* @param _to address to which amount is transferred
* @param _amount to which amount is transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
) public returns (bool success)
{
require(balanceOf[_from] >= _amount);
require(allowed[_from][msg.sender] >= _amount);
require(_amount > 0);
require(_to != address(0));
require(_to != msg.sender);
balanceOf[_from] = balanceOf[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
return true;
}
/* This function allows _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.
* @param _spender address of the spender
* @param _amount amount allowed to be withdrawal
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(_spender != msg.sender);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/* This function returns the amount of tokens approved by the owner that can be
* transferred to the spender's account
* @param _owner address of the owner
* @param _spender address of the spender
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
//This is the Main Railz Token Contract derived from the other two contracts Owned and ERC20
contract RailzToken is Owned, ERC20 {
using SafeMath for uint256;
uint256 tokenSupply = 2000000000; //2 billions
// This notifies clients about the amount burnt , only admin is able to burn the contract
event Burn(address from, uint256 value);
/* This is the main Token Constructor
* @param _centralAdmin Address of the admin of the contract
*/
function RailzToken()
ERC20 (tokenSupply,"Railz","RLZ") public
{
owner = msg.sender;
}
/* This function is used to mint additional tokens
* only admin can invoke this function
* @param _mintedAmount amount of tokens to be minted
*/
function mintTokens(uint256 _mintedAmount) public onlyOwner {
balanceOf[owner] = balanceOf[owner].add(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
Transfer(0, owner, _mintedAmount);
}
/**
* This function Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner {
require(_value <= balanceOf[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balanceOf[burner] = balanceOf[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/* This function is used to lock a user's token , tokens once locked cannot be transferred
* only admin can invoke this function
* @param _target address of the target
*/
function lockAccount(address _target) public onlyOwner {
require(_target != address(0));
isLockedAccount[_target] = true;
}
/* This function is used to unlock a user's already locked tokens
* only admin can invoke this function
* @param _target address of the target
*/
function unlockAccount(address _target) public onlyOwner {
require(_target != address(0));
isLockedAccount[_target] = false;
}
}
|
This function allows _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. _spender address of the spender _amount amount allowed to be withdrawal/
|
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(_spender != msg.sender);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
| 15,333,271
|
./partial_match/56/0xf06f5146644dbfA355018c1801Ae8f508919C22c/sources/MasterChef.sol
|
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with `errorMessage` as a fallback revert reason when `abq` reverts. _Available since v3.1._/
|
function functionCall(address abq, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(abq, data, 0, errorMessage);
}
| 11,279,114
|
./partial_match/42/0x2528aBc12A394fb45f870F518Ab4701371723976/sources/AssetsSnapshot.sol
|
end sync snapshots sync completed but not replaced,set syncFlag to 2.
|
function endSyncSnapshot(uint32 endTotalNum) public returns (bool success){
require(owner == msg.sender,"Only the creator can do this");
require(syncFlag == 1,"Abnormal synchronization status");
require(syncCounter == totalUsers,"The number of uploaded snapshots does not match expectations");
require(syncCounter == endTotalNum,"The number of uploaded snapshots does not match the number of confirmations");
syncFlag = 2;
success = true;
}
| 3,454,936
|
/*
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.
*/
pragma solidity 0.5.10;
pragma experimental ABIEncoderV2;
import "ROOT/0x/utils/contracts/src/LibRichErrors.sol";
import "ROOT/0x/utils/contracts/src/LibSafeMath.sol";
import "ROOT/0x/staking/contracts/src/libs/LibCobbDouglas.sol";
import "ROOT/0x/staking/contracts/src/libs/LibStakingRichErrors.sol";
import "ROOT/0x/staking/contracts/src/interfaces/IStructs.sol";
import "ROOT/0x/staking/contracts/src/staking_pools/MixinStakingPoolRewards.sol";
contract MixinFinalizer is
MixinStakingPoolRewards
{
using LibSafeMath for uint256;
/// @dev Begins a new epoch, preparing the prior one for finalization.
/// Throws if not enough time has passed between epochs or if the
/// previous epoch was not fully finalized.
/// @return numPoolsToFinalize The number of unfinalized pools.
function endEpoch()
external
returns (uint256)
{
uint256 currentEpoch_ = currentEpoch;
uint256 prevEpoch = currentEpoch_.safeSub(1);
// Make sure the previous epoch has been fully finalized.
uint256 numPoolsToFinalizeFromPrevEpoch = aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize;
if (numPoolsToFinalizeFromPrevEpoch != 0) {
revert();
}
// Convert all ETH to WETH; the WETH balance of this contract is the total rewards.
_wrapEth();
// Load aggregated stats for the epoch we're ending.
aggregatedStatsByEpoch[currentEpoch_].rewardsAvailable = _getAvailableWethBalance();
IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[currentEpoch_];
// Emit an event.
emit EpochEnded(
currentEpoch_,
aggregatedStats.numPoolsToFinalize,
aggregatedStats.rewardsAvailable,
aggregatedStats.totalFeesCollected,
aggregatedStats.totalWeightedStake
);
// Advance the epoch. This will revert if not enough time has passed.
_goToNextEpoch();
// If there are no pools to finalize then the epoch is finalized.
if (aggregatedStats.numPoolsToFinalize == 0) {
emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable);
}
return aggregatedStats.numPoolsToFinalize;
}
/// @dev Instantly finalizes a single pool that earned rewards in the previous
/// epoch, crediting it rewards for members and withdrawing operator's
/// rewards as WETH. This can be called by internal functions that need
/// to finalize a pool immediately. Does nothing if the pool is already
/// finalized or did not earn rewards in the previous epoch.
/// @param poolId The pool ID to finalize.
function finalizePool(bytes32 poolId)
external
{
// Compute relevant epochs
uint256 currentEpoch_ = currentEpoch;
uint256 prevEpoch = currentEpoch_.safeSub(1);
// Load the aggregated stats into memory; noop if no pools to finalize.
IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[prevEpoch];
if (aggregatedStats.numPoolsToFinalize == 0) {
return;
}
// Noop if the pool did not earn rewards or already finalized (has no fees).
IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
if (poolStats.feesCollected == 0) {
return;
}
// Clear the pool stats so we don't finalize it again, and to recoup
// some gas.
delete poolStatsByEpoch[poolId][prevEpoch];
// Compute the rewards.
uint256 rewards = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStats);
// Pay the operator and update rewards for the pool.
// Note that we credit at the CURRENT epoch even though these rewards
// were earned in the previous epoch.
(uint256 operatorReward, uint256 membersReward) = _syncPoolRewards(
poolId,
rewards,
poolStats.membersStake
);
// Emit an event.
emit RewardsPaid(
currentEpoch_,
poolId,
operatorReward,
membersReward
);
uint256 totalReward = operatorReward.safeAdd(membersReward);
// Increase `totalRewardsFinalized`.
aggregatedStatsByEpoch[prevEpoch].totalRewardsFinalized =
aggregatedStats.totalRewardsFinalized =
aggregatedStats.totalRewardsFinalized.safeAdd(totalReward);
// Decrease the number of unfinalized pools left.
aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize =
aggregatedStats.numPoolsToFinalize =
aggregatedStats.numPoolsToFinalize.safeSub(1);
// If there are no more unfinalized pools remaining, the epoch is
// finalized.
if (aggregatedStats.numPoolsToFinalize == 0) {
emit EpochFinalized(
prevEpoch,
aggregatedStats.totalRewardsFinalized,
aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized)
);
}
}
/// @dev Computes the reward owed to a pool during finalization.
/// Does nothing if the pool is already finalized.
/// @param poolId The pool's ID.
/// @return totalReward The total reward owed to a pool.
/// @return membersStake The total stake for all non-operator members in
/// this pool.
function _getUnfinalizedPoolRewards(bytes32 poolId)
internal
view
returns (
uint256 reward,
uint256 membersStake
)
{
uint256 prevEpoch = currentEpoch.safeSub(1);
IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
reward = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStatsByEpoch[prevEpoch]);
membersStake = poolStats.membersStake;
}
/// @dev Converts the entire ETH balance of this contract into WETH.
function _wrapEth()
internal
{
uint256 ethBalance = address(this).balance;
if (ethBalance != 0) {
getWethContract().deposit.value(ethBalance)();
}
}
/// @dev Returns the WETH balance of this contract, minus
/// any WETH that has already been reserved for rewards.
function _getAvailableWethBalance()
internal
view
returns (uint256 wethBalance)
{
wethBalance = getWethContract().balanceOf(address(this))
.safeSub(wethReservedForPoolRewards);
return wethBalance;
}
/// @dev Asserts that a pool has been finalized last epoch.
/// @param poolId The id of the pool that should have been finalized.
function _assertPoolFinalizedLastEpoch(bytes32 poolId)
internal
view
{
uint256 prevEpoch = currentEpoch.safeSub(1);
IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
// A pool that has any fees remaining has not been finalized
if (poolStats.feesCollected != 0) {
revert();
}
}
/// @dev Computes the reward owed to a pool during finalization.
/// @param poolStats Stats for a specific pool.
/// @param aggregatedStats Stats aggregated across all pools.
/// @return rewards Unfinalized rewards for the input pool.
function _getUnfinalizedPoolRewardsFromPoolStats(
IStructs.PoolStats memory poolStats,
IStructs.AggregatedStats memory aggregatedStats
)
private
view
returns (uint256 rewards)
{
// There can't be any rewards if the pool did not collect any fees.
if (poolStats.feesCollected == 0) {
return rewards;
}
// Use the cobb-douglas function to compute the total reward.
rewards = LibCobbDouglas.cobbDouglas(
aggregatedStats.rewardsAvailable,
poolStats.feesCollected,
aggregatedStats.totalFeesCollected,
poolStats.weightedStake,
aggregatedStats.totalWeightedStake,
cobbDouglasAlphaNumerator,
cobbDouglasAlphaDenominator
);
// Clip the reward to always be under
// `rewardsAvailable - totalRewardsPaid`,
// in case cobb-douglas overflows, which should be unlikely.
uint256 rewardsRemaining = aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized);
if (rewardsRemaining < rewards) {
rewards = rewardsRemaining;
}
}
}
|
Computes the reward owed to a pool during finalization. Does nothing if the pool is already finalized. poolId The pool's ID. return totalReward The total reward owed to a pool. return membersStake The total stake for all non-operator members in this pool.
|
function _getUnfinalizedPoolRewards(bytes32 poolId)
internal
view
returns (
uint256 reward,
uint256 membersStake
)
{
uint256 prevEpoch = currentEpoch.safeSub(1);
IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
reward = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStatsByEpoch[prevEpoch]);
membersStake = poolStats.membersStake;
}
| 1,014,034
|
pragma solidity >=0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
struct Airline {
uint id;
bool fundPaid;
bool isAccepted;
uint[] votes;
}
struct Flight{
uint id;
bytes32 key;
address airlineAddress;
string flightCode;
uint8 departureStatusCode;
uint departureTimestamp;
uint updatedTimestamp;
}
enum InsuranceState {Sleeping, Expired, Refunded}
struct Insurance{
uint id;
uint flightId;
uint amountPaid;
address passenger;
InsuranceState state;
}
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
uint countAirlines = 0;
uint countFlights = 0;
uint countInsurance = 0;
address contractOwner; // Account used to deploy contract
bool operational = true; // Blocks all state changes throughout the contract if false
// uint minAirlinePercentageApproval = 0.50;
mapping(address => Airline) airlines;
mapping(uint => Flight) flights;
mapping(bytes32 => uint) flightKeyToId;
mapping(uint => uint[]) flightToInsurances;
mapping(uint => Insurance) insurances;
mapping(address => uint[]) passengerToInsuranceIds;
mapping(address => bool) authorizedCallers;
mapping(address => uint) addressToFunds;
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor()
public
payable
{
contractOwner = msg.sender;
authorizedCallers[address(this)] = true;
authorizedCallers[contractOwner] = true;
//Register contract owner as ailine, activate and make the first deposit
_registerAirline(contractOwner, contractOwner);
activateAirline(contractOwner);
payRegistrationFee(contractOwner);
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event ContractModeChanged(bool isOperational);
event NewAirlineAdded(uint id, address airlineAddress);
event NewFlightAdded(uint id, string flightCode);
event NewInsuranceAdded(uint id, uint fligthId, address owner);
event NewVoteForAirline(uint id, uint howMany);
event AirlineAcceptedByMembers(uint id);
event AirlineRegistrationFeePayed(uint id);
event PassengerFundCredited(uint insuranceId, address passengerAddress);
event PassengerFundWithDrawal(address owner, uint amount);
event FlightDepartureUpdated(uint id, uint8 status);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// region Modifiers
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireAuthorization()
{
require(authorizedCallers[msg.sender], "You are not authorized porra!");
_;
}
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAirlines(address airlineAddress) {
require (airlines[airlineAddress].id > 0, "The sender is not an Airline operator");
_;
}
modifier requireAirlineNotRegistered(address airlineAddress) {
require (airlines[airlineAddress].id == 0, "The address is already in use");
_;
}
modifier requireAirlineOperable(address airlineAddress)
{
require (airlines[airlineAddress].fundPaid &&
airlines[airlineAddress].isAccepted,
"The Airline has not the minimum amount on ether to operate");
_;
}
modifier requireNotVoteYet(
address candidate,
address voter
)
{
uint[] memory votes = airlines[candidate].votes;
uint idApprover = airlines[voter].id;
bool found = false;
for (uint i = 0; i < votes.length; i++) {
if(votes[i]==idApprover){
found = true;
break;
}
}
require (!found, "You already vote for this new Airlane");
_;
}
modifier requireInsurance(uint id) {
require(insurances[id].id > 0, "Insurance do not exist");
_;
}
modifier requireInsuranceState(uint id, InsuranceState state) {
require(insurances[id].state == state, "Insurance not in the expected state.");
_;
}
modifier requireFligth(uint id){
require(flights[id].id > 0, "Flight do not exist!");
_;
}
modifier requireFligthOnTime(uint id){
// require(flights[id].departureTimestamp > now, "Flight has already departed!");
_;
}
modifier requirePassengerFunds
(
address _address,
uint amount
)
{
require(amount <= addressToFunds[_address], "The passenger has no funds!");
_;
}
modifier requireContractFunds
(
uint amount
)
{
require(address(this).balance >= amount, "Bankrupt =D");
_;
}
modifier requireDiferentMode(bool mode) {
require(isOperational() != mode, "Contract already in this mode!");
_;
}
modifier requireCandidate(address candidate) {
require(!airlines[candidate].isAccepted, "The airline has already been accepted!");
_;
}
modifier requireElegible(address airline) {
require(airlines[airline].isAccepted, "The airline need to be voted!");
_;
}
modifier requireNotRegistered(
string memory flightCode,
uint departureTimestamp,
address airlineAddress
) {
bytes32 key = getFlightKey(flightCode, departureTimestamp, airlineAddress);
require(flightKeyToId[key] == 0, "The flight has already been created!");
_;
}
// endregion
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// region Utilities
function isOperational()
public
view
returns(bool)
{
return operational;
}
function setOperatingStatus
(
bool mode
)
external
requireIsOperational
requireAuthorization
requireDiferentMode(mode)
{
operational = mode;
emit ContractModeChanged(mode);
}
function setAuthorizedCaller(
address caller,
bool auth
)
public
requireContractOwner
{
authorizedCallers[caller] = auth;
}
// endregion
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
// region Airline
function registerAirline
(
address candidate,
address promoter
)
external
requireAirlines(promoter)
returns(uint)
{
return _registerAirline(candidate, promoter);
}
function _registerAirline
(
address candidate,
address promoter
)
internal
requireIsOperational
requireAuthorization
requireAirlineNotRegistered(candidate)
returns(uint)
{
countAirlines++;
airlines[candidate].id = countAirlines;
//airlines[candidate].isAccepted = (countAirlines < minAirlineConsensus);
airlines[candidate].votes.push(airlines[promoter].id);
emit NewAirlineAdded(countAirlines, candidate);
return countAirlines;
}
function voteAirlineToOperate (
address candidate,
address voter
)
public
requireIsOperational
requireAuthorization
requireCandidate(candidate)
requireAirlines(voter)
requireAirlineOperable(voter)
requireNotVoteYet(candidate, voter)
{
uint id = airlines[voter].id;
airlines[candidate].votes.push(id);
uint lenVotes = airlines[candidate].votes.length;
emit NewVoteForAirline(airlines[candidate].id, lenVotes);
}
function activateAirline(
address candidate
)
public
requireIsOperational
requireAuthorization
requireCandidate(candidate)
{
airlines[candidate].isAccepted = true;
emit AirlineAcceptedByMembers(airlines[candidate].id);
}
function getAirlineData
(
address airline
)
external
requireIsOperational
requireAuthorization
requireAirlines(airline)
view
returns (uint id, uint[] memory votes, bool isAccepted)
{
id = airlines[airline].id;
votes = airlines[airline].votes;
isAccepted = airlines[airline].isAccepted;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function payRegistrationFee
(
address owner
)
public
requireIsOperational
requireAuthorization
requireElegible(owner)
payable
{
// address payable addr = make_payable(owner);
address(this).transfer(msg.value);
airlines[owner].fundPaid = true;
emit AirlineRegistrationFeePayed(airlines[owner].id);
}
// function make_payable(address x) internal pure returns (address payable) {
// return address(uint160(x));
// }
// endregion
// region Flight
function registerFlight(
string memory flightCode,
uint departureTimestamp,
address airlineAddress
)
public
requireIsOperational
requireAuthorization
requireAirlineOperable(airlineAddress)
requireFligthOnTime(departureTimestamp)
requireNotRegistered(flightCode, departureTimestamp, airlineAddress)
{
countFlights++;
bytes32 key = getFlightKey(flightCode, departureTimestamp, airlineAddress);
flights[countFlights].id = countFlights;
flights[countFlights].key = key;
flights[countFlights].flightCode = flightCode;
flights[countFlights].airlineAddress = airlineAddress;
flights[countFlights].departureTimestamp = departureTimestamp;
flightKeyToId[key] = countFlights;
emit NewFlightAdded(countFlights, flightCode);
}
function getFlightId
(
string memory flightCode,
uint256 departureTimestamp,
address airlineAddress
)
public
requireIsOperational
requireAuthorization
view
returns(uint)
{
bytes32 key = getFlightKey(flightCode, departureTimestamp, airlineAddress);
return flightKeyToId[key];
}
function getFlightKey
(
string memory flightCode,
uint256 departureTimestamp,
address airlineAddress
)
public
requireIsOperational
requireAuthorization
view
returns(bytes32)
{
return keccak256(abi.encodePacked(airlineAddress, flightCode, departureTimestamp));
}
function getFlightIdByKey(bytes32 _key)
external
requireIsOperational
requireAuthorization
requireFligth(flightKeyToId[_key])
view
returns (uint)
{
return flightKeyToId[_key];
}
function getFlight(
uint id
)
external
requireIsOperational
requireAuthorization
requireFligth(id)
view
returns (
bytes32 key,
address airlineAddress,
string memory flightCode,
uint8 departureStatusCode,
uint departureTimestamp,
uint updatedTimestamp
)
{
key = flights[id].key;
airlineAddress = flights[id].airlineAddress;
flightCode = flights[id].flightCode;
departureStatusCode = flights[id].departureStatusCode;
departureTimestamp = flights[id].departureTimestamp;
updatedTimestamp = flights[id].updatedTimestamp;
}
function setFlightDepartureCode(
uint id,
uint8 statusCode
)
external
requireIsOperational
requireAuthorization
requireFligth(id)
{
flights[id].departureStatusCode = statusCode;
flights[id].updatedTimestamp = now;
emit FlightDepartureUpdated(id, statusCode);
}
// endregion
// region Insurance
/**
* @dev Buy insurance for a flight
*
*/
function registerInsurance
(
uint _flightId,
address _owner
)
public
requireIsOperational
requireAuthorization
requireFligth(_flightId)
requireFligthOnTime(_flightId)
payable
{
countInsurance++;
insurances[countInsurance] = Insurance({
id: countInsurance,
flightId: _flightId,
amountPaid: msg.value,
passenger: _owner,
state: InsuranceState.Sleeping
});
flightToInsurances[_flightId].push(countInsurance);
//address(this).transfer(msg.value);
emit NewInsuranceAdded(countInsurance, _flightId, _owner);
}
function getInsurance(uint _id)
public
requireIsOperational
requireAuthorization
requireInsurance(_id)
view
returns (uint flightId, string memory state, uint amountPaid, address owner)
{
Insurance memory insurance = insurances[_id];
flightId = insurance.flightId;
amountPaid = insurance.amountPaid;
owner = insurance.passenger;
if(uint(insurance.state) == 0) {
state = "Sleeping";
}
if(uint(insurance.state) == 1) {
state = "Expired";
}
if(uint(insurance.state) == 2) {
state = "Credited";
}
}
function getInsurancesByFlight(uint _id)
public
requireIsOperational
requireAuthorization
requireFligth(_id)
view
returns (uint[] memory listInsurances)
{
listInsurances = flightToInsurances[_id];
}
// endregion
// region User Fund
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
uint insuranceId,
uint amount
)
public
requireIsOperational
requireAuthorization
requireInsurance(insuranceId)
requireInsuranceState(insuranceId, InsuranceState.Sleeping)
{
Insurance memory i = insurances[insuranceId];
addressToFunds[i.passenger] = addressToFunds[i.passenger].add(amount);
insurances[insuranceId].state = InsuranceState.Refunded;
emit PassengerFundCredited(insuranceId, i.passenger);
}
function withdrawalFund
(
uint amount,
address owner
)
public
requireIsOperational
requireAuthorization
requirePassengerFunds(owner, amount)
requireContractFunds(amount)
payable
{
addressToFunds[owner] = addressToFunds[owner].sub(amount);
owner.transfer(amount);
emit PassengerFundWithDrawal(owner, amount);
}
function getFundBalance (address owner)
public
requireIsOperational
requireAuthorization
view
returns (uint)
{
return addressToFunds[owner];
}
// endregion User Fund
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(uint amount)
internal
{
address(this).transfer(amount);
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
}
// function flightDepartureUpdate
// (uint _id, uint8 _statusCode)
// public
// requireIsOperational
// requireFligth(_id)
// {
// flights[_id].departureStatusCode = _statusCode;
// flights[_id].updatedTimestamp = now;
// emit FlightDepartureUpdated(_id, _statusCode);
// }
}
|
region Insurance Buy insurance for a flight/
|
function registerInsurance
(
uint _flightId,
address _owner
)
public
requireIsOperational
requireAuthorization
requireFligth(_flightId)
requireFligthOnTime(_flightId)
payable
{
countInsurance++;
insurances[countInsurance] = Insurance({
id: countInsurance,
flightId: _flightId,
amountPaid: msg.value,
passenger: _owner,
state: InsuranceState.Sleeping
});
flightToInsurances[_flightId].push(countInsurance);
emit NewInsuranceAdded(countInsurance, _flightId, _owner);
}
| 6,435,520
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.2;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IBoostedVaultWithLockup {
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount) external;
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount) external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last) external;
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external;
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external;
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last) external;
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account) external;
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() external view returns (uint256);
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() external view returns (uint256);
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) external view returns (uint256);
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
returns (
uint256 amount,
uint256 first,
uint256 last
);
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
interface IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
abstract contract InitializableRewardsDistributionRecipient is
IRewardsDistributionRecipient,
ImmutableModule
{
// This address has the ability to distribute the rewards
address public rewardsDistributor;
constructor(address _nexus) ImmutableModule(_nexus) {}
/** @dev Recipient is a module, governed by mStable governance */
function _initialize(address _rewardsDistributor) internal {
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
/**
* @dev Change the rewardsDistributor - only called by mStable governor
* @param _rewardsDistributor Address of the new distributor
*/
function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor {
rewardsDistributor = _rewardsDistributor;
}
}
interface IBoostDirector {
function getBalance(address _user) external returns (uint256);
function setDirection(
address _old,
address _new,
bool _pokeNew
) external;
function whitelistVaults(address[] calldata _vaults) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
/**
* @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);
}
}
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initializeReentrancyGuard() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e38 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
library Root {
/**
* @dev Returns the square root of a given number
* @param x Input
* @return y Square root of Input
*/
function sqrt(uint256 x) internal pure returns (uint256 y) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint256(r < r1 ? r : r1);
}
}
}
contract BoostedTokenWrapper is InitializableReentrancyGuard {
using StableMath for uint256;
using SafeERC20 for IERC20;
event Transfer(address indexed from, address indexed to, uint256 value);
string private _name;
string private _symbol;
IERC20 public immutable stakingToken;
IBoostDirector public immutable boostDirector;
uint256 private _totalBoostedSupply;
mapping(address => uint256) private _boostedBalances;
mapping(address => uint256) private _rawBalances;
// Vars for use in the boost calculations
uint256 private constant MIN_DEPOSIT = 1e18;
uint256 private constant MAX_VMTA = 400000e18;
uint256 private constant MAX_BOOST = 3e18;
uint256 private constant MIN_BOOST = 1e18;
uint256 private constant FLOOR = 95e16;
uint256 public immutable boostCoeff; // scaled by 10
uint256 public immutable priceCoeff;
/**
* @dev TokenWrapper constructor
* @param _stakingToken Wrapped token to be staked
* @param _boostDirector vMTA boost director
* @param _priceCoeff Rough price of a given LP token, to be used in boost calculations, where $1 = 1e18
*/
constructor(
address _stakingToken,
address _boostDirector,
uint256 _priceCoeff,
uint256 _boostCoeff
) {
stakingToken = IERC20(_stakingToken);
boostDirector = IBoostDirector(_boostDirector);
priceCoeff = _priceCoeff;
boostCoeff = _boostCoeff;
}
function _initialize(string memory _nameArg, string memory _symbolArg) internal {
_initializeReentrancyGuard();
_name = _nameArg;
_symbol = _symbolArg;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev Get the total boosted amount
* @return uint256 total supply
*/
function totalSupply() public view returns (uint256) {
return _totalBoostedSupply;
}
/**
* @dev Get the boosted balance of a given account
* @param _account User for which to retrieve balance
*/
function balanceOf(address _account) public view returns (uint256) {
return _boostedBalances[_account];
}
/**
* @dev Get the RAW balance of a given account
* @param _account User for which to retrieve balance
*/
function rawBalanceOf(address _account) public view returns (uint256) {
return _rawBalances[_account];
}
/**
* @dev Read the boost for the given address
* @param _account User for which to return the boost
* @return boost where 1x == 1e18
*/
function getBoost(address _account) public view returns (uint256) {
return balanceOf(_account).divPrecisely(rawBalanceOf(_account));
}
/**
* @dev Deposits a given amount of StakingToken from sender
* @param _amount Units of StakingToken
*/
function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant {
_rawBalances[_beneficiary] += _amount;
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @dev Withdraws a given stake from sender
* @param _amount Units of StakingToken
*/
function _withdrawRaw(uint256 _amount) internal nonReentrant {
_rawBalances[msg.sender] -= _amount;
stakingToken.safeTransfer(msg.sender, _amount);
}
/**
* @dev Updates the boost for the given address according to the formula
* boost = min(0.5 + c * vMTA_balance / imUSD_locked^(7/8), 1.5)
* If rawBalance <= MIN_DEPOSIT, boost is 0
* @param _account User for which to update the boost
*/
function _setBoost(address _account) internal {
uint256 rawBalance = _rawBalances[_account];
uint256 boostedBalance = _boostedBalances[_account];
uint256 boost = MIN_BOOST;
// Check whether balance is sufficient
// is_boosted is used to minimize gas usage
uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18;
if (scaledBalance >= MIN_DEPOSIT) {
uint256 votingWeight = boostDirector.getBalance(_account);
boost = _computeBoost(scaledBalance, votingWeight);
}
uint256 newBoostedBalance = rawBalance.mulTruncate(boost);
if (newBoostedBalance != boostedBalance) {
_totalBoostedSupply = _totalBoostedSupply - boostedBalance + newBoostedBalance;
_boostedBalances[_account] = newBoostedBalance;
if(newBoostedBalance > boostedBalance) {
emit Transfer(address(0), _account, newBoostedBalance - boostedBalance);
} else {
emit Transfer(_account, address(0), boostedBalance - newBoostedBalance);
}
}
}
/**
* @dev Computes the boost for
* boost = min(m, max(1, 0.95 + c * min(voting_weight, f) / deposit^(7/8)))
* @param _scaledDeposit deposit amount in terms of USD
*/
function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight)
private
view
returns (uint256 boost)
{
if (_votingWeight == 0) return MIN_BOOST;
// Compute balance to the power 7/8
// if price is $0.10, do sqrt(_deposit * 1e5)
// if price is $1.00, do sqrt(_deposit * 1e6)
// if price is $10000.00, do sqrt(_deposit * 1e9)
uint256 denominator = Root.sqrt(Root.sqrt(Root.sqrt(_scaledDeposit * 1e6)));
denominator =
denominator *
denominator *
denominator *
denominator *
denominator *
denominator *
denominator;
denominator /= 1e3;
boost = (((StableMath.min(_votingWeight, MAX_VMTA) * boostCoeff) / 10) * 1e18) / denominator;
boost = StableMath.min(MAX_BOOST, StableMath.max(MIN_BOOST, FLOOR + boost));
}
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// Internal
// Libs
/**
* @title BoostedSavingsVault
* @author mStable
* @notice Accrues rewards second by second, based on a users boosted balance
* @dev Forked from rewards/staking/StakingRewards.sol
* Changes:
* - Lockup implemented in `updateReward` hook (20% unlock immediately, 80% locked for 6 months)
* - `updateBoost` hook called after every external action to reset a users boost
* - Struct packing of common data
* - Searching for and claiming of unlocked rewards
*/
contract BoostedSavingsVault is
IBoostedVaultWithLockup,
Initializable,
InitializableRewardsDistributionRecipient,
BoostedTokenWrapper
{
using SafeERC20 for IERC20;
using StableMath for uint256;
using SafeCast for uint256;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address payer);
event Withdrawn(address indexed user, uint256 amount);
event Poked(address indexed user);
event RewardPaid(address indexed user, uint256 reward);
IERC20 public immutable rewardsToken;
uint64 public constant DURATION = 7 days;
// Length of token lockup, after rewards are earned
uint256 public constant LOCKUP = 26 weeks;
// Percentage of earned tokens unlocked immediately
uint64 public constant UNLOCK = 33e16;
// Timestamp for current period finish
uint256 public periodFinish;
// RewardRate for the rest of the PERIOD
uint256 public rewardRate;
// Last time any user took action
uint256 public lastUpdateTime;
// Ever increasing rewardPerToken rate, based on % of total supply
uint256 public rewardPerTokenStored;
mapping(address => UserData) public userData;
// Locked reward tracking
mapping(address => Reward[]) public userRewards;
mapping(address => uint64) public userClaim;
struct UserData {
uint128 rewardPerTokenPaid;
uint128 rewards;
uint64 lastAction;
uint64 rewardCount;
}
struct Reward {
uint64 start;
uint64 finish;
uint128 rate;
}
constructor(
address _nexus,
address _stakingToken,
address _boostDirector,
uint256 _priceCoeff,
uint256 _coeff,
address _rewardsToken
)
InitializableRewardsDistributionRecipient(_nexus)
BoostedTokenWrapper(_stakingToken, _boostDirector, _priceCoeff, _coeff)
{
rewardsToken = IERC20(_rewardsToken);
}
/**
* @dev StakingRewards is a TokenWrapper and RewardRecipient
* Constants added to bytecode at deployTime to reduce SLOAD cost
*/
function initialize(address _rewardsDistributor, string calldata _nameArg, string calldata _symbolArg) external initializer {
InitializableRewardsDistributionRecipient._initialize(_rewardsDistributor);
BoostedTokenWrapper._initialize(_nameArg, _symbolArg);
}
/**
* @dev Updates the reward for a given address, before executing function.
* Locks 80% of new rewards up for 6 months, vesting linearly from (time of last action + 6 months) to
* (now + 6 months). This allows rewards to be distributed close to how they were accrued, as opposed
* to locking up for a flat 6 months from the time of this fn call (allowing more passive accrual).
*/
modifier updateReward(address _account) {
uint256 currentTime = block.timestamp;
uint64 currentTime64 = SafeCast.toUint64(currentTime);
// Setting of global vars
(uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken();
// If statement protects against loss in initialisation case
if (newRewardPerToken > 0) {
rewardPerTokenStored = newRewardPerToken;
lastUpdateTime = lastApplicableTime;
// Setting of personal vars based on new globals
if (_account != address(0)) {
UserData memory data = userData[_account];
uint256 earned_ = _earned(_account, data.rewardPerTokenPaid, newRewardPerToken);
// If earned == 0, then it must either be the initial stake, or an action in the
// same block, since new rewards unlock after each block.
if (earned_ > 0) {
uint256 unlocked = earned_.mulTruncate(UNLOCK);
uint256 locked = earned_ - unlocked;
userRewards[_account].push(
Reward({
start: SafeCast.toUint64(LOCKUP + data.lastAction),
finish: SafeCast.toUint64(LOCKUP + currentTime),
rate: SafeCast.toUint128(locked / (currentTime - data.lastAction))
})
);
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: SafeCast.toUint128(unlocked + data.rewards),
lastAction: currentTime64,
rewardCount: data.rewardCount + 1
});
} else {
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: data.rewards,
lastAction: currentTime64,
rewardCount: data.rewardCount
});
}
}
} else if (_account != address(0)) {
// This should only be hit once, for first staker in initialisation case
userData[_account].lastAction = currentTime64;
}
_;
}
/** @dev Updates the boost for a given address, after the rest of the function has executed */
modifier updateBoost(address _account) {
_;
_setBoost(_account);
}
/***************************************
ACTIONS - EXTERNAL
****************************************/
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_stake(msg.sender, _amount);
}
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount)
external
override
updateReward(_beneficiary)
updateBoost(_beneficiary)
{
_stake(_beneficiary, _amount);
}
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external override updateReward(msg.sender) updateBoost(msg.sender) {
_withdraw(rawBalanceOf(msg.sender));
(uint256 first, uint256 last) = _unclaimedEpochs(msg.sender);
_claimRewards(first, last);
}
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_withdraw(rawBalanceOf(msg.sender));
_claimRewards(_first, _last);
}
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_withdraw(_amount);
}
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external override updateReward(msg.sender) updateBoost(msg.sender) {
uint256 unlocked = userData[msg.sender].rewards;
userData[msg.sender].rewards = 0;
if (unlocked > 0) {
rewardsToken.safeTransfer(msg.sender, unlocked);
emit RewardPaid(msg.sender, unlocked);
}
}
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external override updateReward(msg.sender) updateBoost(msg.sender) {
(uint256 first, uint256 last) = _unclaimedEpochs(msg.sender);
_claimRewards(first, last);
}
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_claimRewards(_first, _last);
}
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account)
external
override
updateReward(_account)
updateBoost(_account)
{
emit Poked(_account);
}
/***************************************
ACTIONS - INTERNAL
****************************************/
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function _claimRewards(uint256 _first, uint256 _last) internal {
(uint256 unclaimed, uint256 lastTimestamp) = _unclaimedRewards(msg.sender, _first, _last);
userClaim[msg.sender] = uint64(lastTimestamp);
uint256 unlocked = userData[msg.sender].rewards;
userData[msg.sender].rewards = 0;
uint256 total = unclaimed + unlocked;
if (total > 0) {
rewardsToken.safeTransfer(msg.sender, total);
emit RewardPaid(msg.sender, total);
}
}
/**
* @dev Internally stakes an amount by depositing from sender,
* and crediting to the specified beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function _stake(address _beneficiary, uint256 _amount) internal {
require(_amount > 0, "Cannot stake 0");
require(_beneficiary != address(0), "Invalid beneficiary address");
_stakeRaw(_beneficiary, _amount);
emit Staked(_beneficiary, _amount, msg.sender);
}
/**
* @dev Withdraws raw units from the sender
* @param _amount Units of StakingToken
*/
function _withdraw(uint256 _amount) internal {
require(_amount > 0, "Cannot withdraw 0");
_withdrawRaw(_amount);
emit Withdrawn(msg.sender, _amount);
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the RewardsToken
*/
function getRewardToken() external view override returns (IERC20) {
return rewardsToken;
}
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() public view override returns (uint256) {
return StableMath.min(block.timestamp, periodFinish);
}
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() public view override returns (uint256) {
(uint256 rewardPerToken_, ) = _rewardPerToken();
return rewardPerToken_;
}
function _rewardPerToken()
internal
view
returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)
{
uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD
uint256 timeDelta = lastApplicableTime - lastUpdateTime; // + 1 SLOAD
// If this has been called twice in the same block, shortcircuit to reduce gas
if (timeDelta == 0) {
return (rewardPerTokenStored, lastApplicableTime);
}
// new reward units to distribute = rewardRate * timeSinceLastUpdate
uint256 rewardUnitsToDistribute = rewardRate * timeDelta; // + 1 SLOAD
uint256 supply = totalSupply(); // + 1 SLOAD
// If there is no StakingToken liquidity, avoid div(0)
// If there is nothing to distribute, short circuit
if (supply == 0 || rewardUnitsToDistribute == 0) {
return (rewardPerTokenStored, lastApplicableTime);
}
// new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply);
// return summed rate
return (rewardPerTokenStored + unitsToDistributePerToken, lastApplicableTime); // + 1 SLOAD
}
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) public view override returns (uint256) {
uint256 newEarned =
_earned(_account, userData[_account].rewardPerTokenPaid, rewardPerToken());
uint256 immediatelyUnlocked = newEarned.mulTruncate(UNLOCK);
return immediatelyUnlocked + userData[_account].rewards;
}
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
override
returns (
uint256 amount,
uint256 first,
uint256 last
)
{
(first, last) = _unclaimedEpochs(_account);
(uint256 unlocked, ) = _unclaimedRewards(_account, first, last);
amount = unlocked + earned(_account);
}
/** @dev Returns only the most recently earned rewards */
function _earned(
address _account,
uint256 _userRewardPerTokenPaid,
uint256 _currentRewardPerToken
) internal view returns (uint256) {
// current rate per token - rate user previously received
uint256 userRewardDelta = _currentRewardPerToken - _userRewardPerTokenPaid; // + 1 SLOAD
// Short circuit if there is nothing new to distribute
if (userRewardDelta == 0) {
return 0;
}
// new reward = staked tokens * difference in rate
uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD
// add to previous rewards
return userNewReward;
}
/**
* @dev Gets the first and last indexes of array elements containing unclaimed rewards
*/
function _unclaimedEpochs(address _account)
internal
view
returns (uint256 first, uint256 last)
{
uint64 lastClaim = userClaim[_account];
uint256 firstUnclaimed = _findFirstUnclaimed(lastClaim, _account);
uint256 lastUnclaimed = _findLastUnclaimed(_account);
return (firstUnclaimed, lastUnclaimed);
}
/**
* @dev Sums the cumulative rewards from a valid range
*/
function _unclaimedRewards(
address _account,
uint256 _first,
uint256 _last
) internal view returns (uint256 amount, uint256 latestTimestamp) {
uint256 currentTime = block.timestamp;
uint64 lastClaim = userClaim[_account];
// Check for no rewards unlocked
uint256 totalLen = userRewards[_account].length;
if (_first == 0 && _last == 0) {
if (totalLen == 0 || currentTime <= userRewards[_account][0].start) {
return (0, currentTime);
}
}
// If there are previous unlocks, check for claims that would leave them untouchable
if (_first > 0) {
require(
lastClaim >= userRewards[_account][_first - 1].finish,
"Invalid _first arg: Must claim earlier entries"
);
}
uint256 count = _last - _first + 1;
for (uint256 i = 0; i < count; i++) {
uint256 id = _first + i;
Reward memory rwd = userRewards[_account][id];
require(currentTime >= rwd.start && lastClaim <= rwd.finish, "Invalid epoch");
uint256 endTime = StableMath.min(rwd.finish, currentTime);
uint256 startTime = StableMath.max(rwd.start, lastClaim);
uint256 unclaimed = (endTime - startTime) * rwd.rate;
amount += unclaimed;
}
// Calculate last relevant timestamp here to allow users to avoid issue of OOG errors
// by claiming rewards in batches.
latestTimestamp = StableMath.min(currentTime, userRewards[_account][_last].finish);
}
/**
* @dev Uses binarysearch to find the unclaimed lockups for a given account
*/
function _findFirstUnclaimed(uint64 _lastClaim, address _account)
internal
view
returns (uint256 first)
{
uint256 len = userRewards[_account].length;
if (len == 0) return 0;
// Binary search
uint256 min = 0;
uint256 max = len - 1;
// Will be always enough for 128-bit numbers
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
if (_lastClaim > userRewards[_account][mid].start) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
/**
* @dev Uses binarysearch to find the unclaimed lockups for a given account
*/
function _findLastUnclaimed(address _account) internal view returns (uint256 first) {
uint256 len = userRewards[_account].length;
if (len == 0) return 0;
// Binary search
uint256 min = 0;
uint256 max = len - 1;
// Will be always enough for 128-bit numbers
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
if (block.timestamp > userRewards[_account][mid].start) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
/***************************************
ADMIN
****************************************/
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of RewardToken that have been added to the pool
*/
function notifyRewardAmount(uint256 _reward)
external
override
onlyRewardsDistributor
updateReward(address(0))
{
require(_reward < 1e24, "Cannot notify with more than a million units");
uint256 currentTime = block.timestamp;
// If previous period over, reset rewardRate
if (currentTime >= periodFinish) {
rewardRate = _reward / DURATION;
}
// If additional reward to existing period, calc sum
else {
uint256 remaining = periodFinish - currentTime;
uint256 leftover = remaining * rewardRate;
rewardRate = (_reward + leftover) / DURATION;
}
lastUpdateTime = currentTime;
periodFinish = currentTime + DURATION;
emit RewardAdded(_reward);
}
}
|
This address has the ability to distribute the rewards
|
{
address public rewardsDistributor;
constructor(address _nexus) ImmutableModule(_nexus) {}
function _initialize(address _rewardsDistributor) internal {
rewardsDistributor = _rewardsDistributor;
}
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor {
rewardsDistributor = _rewardsDistributor;
}
}
| 322,441
|
pragma solidity 0.8.10;
// Copyright Balancer, BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import "./BToken.sol";
import "./BMath.sol";
import "../../interfaces/ISideStaking.sol";
import "../../utils/SafeERC20.sol";
/**
* @title BPool
*
* @dev Used by the (Ocean version) BFactory contract as a bytecode reference to
* deploy new BPools.
*
* This contract is a friendly fork of Balancer [1]
* [1] https://github.com/balancer-labs/balancer-core/contracts/.
* All fees are expressed in wei. Examples:
* (1e17 = 10 % , 1e16 = 1% , 1e15 = 0.1%, 1e14 = 0.01%)
*/
contract BPool is BMath, BToken {
using SafeERC20 for IERC20;
struct Record {
bool bound; // is token bound to pool
uint256 index; // private
uint256 denorm; // denormalized weight
uint256 balance;
}
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut,
uint256 timestamp
);
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn,
uint256 timestamp
);
event LOG_SETUP(
address indexed caller,
address indexed baseToken,
uint256 baseTokenAmountIn,
uint256 baseTokenWeight,
address indexed datatoken,
uint256 datatokenAmountIn,
uint256 datatokenWeight
);
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut,
uint256 timestamp
);
event LOG_CALL(
bytes4 indexed sig,
address indexed caller,
uint256 timestamp,
bytes data
);
event LOG_BPT(uint256 bptAmount);
event LOG_BPT_SS(uint256 bptAmount); //emitted for SS contract
event OPCFee(
address caller,
address OPCWallet,
address token,
uint256 amount
);
event SwapFeeChanged(address caller, uint256 amount);
event PublishMarketFee(
address caller,
address marketAddress,
address token,
uint256 amount
);
// emited for fees sent to consumeMarket
event ConsumeMarketFee(address to, address token, uint256 amount);
event SWAP_FEES(uint LPFeeAmount, uint oceanFeeAmount, uint marketFeeAmount,
uint consumeMarketFeeAmount, address tokenFeeAddress);
//emitted for every change done by publisherMarket
event PublishMarketFeeChanged(address caller, address newMarketCollector, uint256 swapFee);
modifier _lock_() {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _viewlock_() {
require(!_mutex, "ERR_REENTRY");
_;
}
bool private _mutex;
address private _controller; // has CONTROL role
bool private _publicSwap; // true if PUBLIC can call SWAP functions
//address public _publishMarketCollector;
address public _publishMarketCollector;
address public _opcCollector;
// `setSwapFee` and `finalize` require CONTROL
// `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN`
bool private _finalized;
address[] private _tokens;
mapping(address => Record) private _records;
uint256 private _totalWeight;
ISideStaking ssContract;
//-----------------------------------------------------------------------
//Proxy contract functionality: begin
bool private initialized;
/**
* @dev getId
* Return template id in case we need different ABIs.
* If you construct your own template, please make sure to change the hardcoded value
*/
function getId() pure public returns (uint8) {
return 1;
}
function isInitialized() external view returns (bool) {
return initialized;
}
// Called prior to contract initialization (e.g creating new BPool instance)
// Calls private _initialize function. Only if contract is not initialized.
function initialize(
address controller,
address factory,
uint256[] calldata swapFees,
bool publicSwap,
bool finalized,
address[2] calldata tokens,
address[2] calldata feeCollectors
) external returns (bool) {
require(!initialized, "ERR_ALREADY_INITIALIZED");
require(controller != address(0), "ERR_INVALID_CONTROLLER_ADDRESS");
require(factory != address(0), "ERR_INVALID_FACTORY_ADDRESS");
require(swapFees[0] >= MIN_FEE, "ERR_MIN_FEE");
require(swapFees[0] <= MAX_FEE, "ERR_MAX_FEE");
require(swapFees[1] == 0 || swapFees[1]>= MIN_FEE, "ERR_MIN_FEE");
require(swapFees[1] <= MAX_FEE, "ERR_MAX_FEE");
return
_initialize(
controller,
factory,
swapFees,
publicSwap,
finalized,
tokens,
feeCollectors
);
}
// Private function called on contract initialization.
function _initialize(
address controller,
address factory,
uint256[] memory swapFees,
bool publicSwap,
bool finalized,
address[2] memory tokens,
address[2] memory feeCollectors
) private returns (bool) {
_controller = controller;
_factory = factory;
_swapFee = swapFees[0];
emit SwapFeeChanged(msg.sender, _swapFee);
_swapPublishMarketFee = swapFees[1];
_publicSwap = publicSwap;
_finalized = finalized;
_datatokenAddress = tokens[0];
_baseTokenAddress = tokens[1];
_publishMarketCollector = feeCollectors[0];
emit PublishMarketFeeChanged(msg.sender, _publishMarketCollector, _swapPublishMarketFee);
_opcCollector = feeCollectors[1];
initialized = true;
ssContract = ISideStaking(_controller);
return initialized;
}
/**
* @dev setup
* Initial setup of the pool
* Can be called only by the controller
* @param datatokenAddress datatokenAddress
* @param datatokenAmount how many datatokens in the initial reserve
* @param datatokenWeight datatoken weight (hardcoded in deployer at 50%)
* @param baseTokenAddress base token
* @param baseTokenAmount how many basetokens in the initial reserve
* @param baseTokenWeight base weight (hardcoded in deployer at 50%)
*/
function setup(
address datatokenAddress,
uint256 datatokenAmount,
uint256 datatokenWeight,
address baseTokenAddress,
uint256 baseTokenAmount,
uint256 baseTokenWeight
) external _lock_ {
require(msg.sender == _controller, "ERR_INVALID_CONTROLLER");
require(
datatokenAddress == _datatokenAddress,
"ERR_INVALID_DATATOKEN_ADDRESS"
);
require(
baseTokenAddress == _baseTokenAddress,
"ERR_INVALID_baseToken_ADDRESS"
);
// other inputs will be validated prior
// calling the below functions
// bind datatoken
bind(datatokenAddress, datatokenAmount, datatokenWeight);
emit LOG_JOIN(
msg.sender,
datatokenAddress,
datatokenAmount,
block.timestamp
);
// bind baseToken
bind(baseTokenAddress, baseTokenAmount, baseTokenWeight);
emit LOG_JOIN(
msg.sender,
baseTokenAddress,
baseTokenAmount,
block.timestamp
);
// finalize
finalize();
emit LOG_SETUP(
msg.sender,
baseTokenAddress,
baseTokenAmount,
baseTokenWeight,
datatokenAddress,
datatokenAmount,
datatokenWeight
);
}
//Proxy contract functionality: end
//-----------------------------------------------------------------------
/**
* @dev isPublicSwap
* Returns true if swapping is allowed
*/
function isPublicSwap() external view returns (bool) {
return _publicSwap;
}
/**
* @dev isFinalized
* Returns true if pool is finalized
*/
function isFinalized() external view returns (bool) {
return _finalized;
}
/**
* @dev isBound
* Returns true if token is bound
* @param t token to be checked
*/
function isBound(address t) external view returns (bool) {
return _records[t].bound;
}
function _checkBound(address token) internal view {
require(_records[token].bound, "ERR_NOT_BOUND");
}
/**
* @dev getNumTokens
* Returns number of tokens bounded to pool
*/
function getNumTokens() external view returns (uint256) {
return _tokens.length;
}
/**
* @dev getCurrentTokens
* Returns tokens bounded to pool, before the pool is finalized
*/
function getCurrentTokens()
external
view
_viewlock_
returns (address[] memory tokens)
{
return _tokens;
}
/**
* @dev getFinalTokens
* Returns tokens bounded to pool, after the pool was finalized
*/
function getFinalTokens()
public
view
_viewlock_
returns (address[] memory tokens)
{
require(_finalized, "ERR_NOT_FINALIZED");
return _tokens;
}
/**
* @dev collectOPC
* Collects and send all OPC Fees to _opcCollector.
* This funtion can be called by anyone, because fees are being sent to _opcCollector
*/
function collectOPC() external {
address[] memory tokens = getFinalTokens();
for (uint256 i = 0; i < tokens.length; i++) {
uint256 amount = communityFees[tokens[i]];
communityFees[tokens[i]] = 0;
IERC20(tokens[i]).safeTransfer(_opcCollector, amount);
emit OPCFee(msg.sender, _opcCollector, tokens[i], amount);
}
}
/**
* @dev getCurrentOPCFees
* Get the current amount of fees which can be withdrawned by OPC
* @return address[] - array of tokens addresses
* uint256[] - array of amounts
*/
function getCurrentOPCFees()
public
view
returns (address[] memory, uint256[] memory)
{
address[] memory poolTokens = getFinalTokens();
address[] memory tokens = new address[](poolTokens.length);
uint256[] memory amounts = new uint256[](poolTokens.length);
for (uint256 i = 0; i < poolTokens.length; i++) {
tokens[i] = poolTokens[i];
amounts[i] = communityFees[poolTokens[i]];
}
return (tokens, amounts);
}
/**
* @dev getCurrentMarketFees
* Get the current amount of fees which can be withdrawned by _publishMarketCollector
* @return address[] - array of tokens addresses
* uint256[] - array of amounts
*/
function getCurrentMarketFees()
public
view
returns (address[] memory, uint256[] memory)
{
address[] memory poolTokens = getFinalTokens();
address[] memory tokens = new address[](poolTokens.length);
uint256[] memory amounts = new uint256[](poolTokens.length);
for (uint256 i = 0; i < poolTokens.length; i++) {
tokens[i] = poolTokens[i];
amounts[i] = publishMarketFees[poolTokens[i]];
}
return (tokens, amounts);
}
/**
* @dev collectMarketFee
* Collects and send all Market Fees to _publishMarketCollector.
* This function can be called by anyone, because fees are being sent to _publishMarketCollector
*/
function collectMarketFee() external {
address[] memory tokens = getFinalTokens();
for (uint256 i = 0; i < tokens.length; i++) {
uint256 amount = publishMarketFees[tokens[i]];
publishMarketFees[tokens[i]] = 0;
IERC20(tokens[i]).safeTransfer(_publishMarketCollector, amount);
emit PublishMarketFee(
msg.sender,
_publishMarketCollector,
tokens[i],
amount
);
}
}
/**
* @dev updatePublishMarketFee
* Set _newCollector as _publishMarketCollector
* @param _newCollector new _publishMarketCollector
* @param _newSwapFee new swapFee
*/
function updatePublishMarketFee(address _newCollector, uint256 _newSwapFee) external {
require(_publishMarketCollector == msg.sender, "ONLY MARKET COLLECTOR");
require(_newCollector != address(0), "Invalid _newCollector address");
require(_newSwapFee ==0 || _newSwapFee >= MIN_FEE, "ERR_MIN_FEE");
require(_newSwapFee <= MAX_FEE, "ERR_MAX_FEE");
_publishMarketCollector = _newCollector;
_swapPublishMarketFee = _newSwapFee;
emit PublishMarketFeeChanged(msg.sender, _publishMarketCollector, _swapPublishMarketFee);
}
/**
* @dev getDenormalizedWeight
* Returns denormalized weight of a token
* @param token token to be checked
*/
function getDenormalizedWeight(address token)
external
view
_viewlock_
returns (uint256)
{
_checkBound(token);
return _records[token].denorm;
}
/**
* @dev getTotalDenormalizedWeight
* Returns total denormalized weught of the pool
*/
function getTotalDenormalizedWeight()
external
view
_viewlock_
returns (uint256)
{
return _totalWeight;
}
/**
* @dev getNormalizedWeight
* Returns normalized weight of a token
* @param token token to be checked
*/
function getNormalizedWeight(address token)
external
view
_viewlock_
returns (uint256)
{
_checkBound(token);
uint256 denorm = _records[token].denorm;
return bdiv(denorm, _totalWeight);
}
/**
* @dev getBalance
* Returns the current token reserve amount
* @param token token to be checked
*/
function getBalance(address token)
external
view
_viewlock_
returns (uint256)
{
_checkBound(token);
return _records[token].balance;
}
/**
* @dev getSwapFee
* Returns the current Liquidity Providers swap fee
*/
function getSwapFee() external view returns (uint256) {
return _swapFee;
}
/**
* @dev getMarketFee
* Returns the current fee of publishingMarket
*/
function getMarketFee() external view returns (uint256) {
return _swapPublishMarketFee;
}
/**
* @dev getController
* Returns the current controller address (ssBot)
*/
function getController() external view returns (address) {
return _controller;
}
/**
* @dev getDatatokenAddress
* Returns the current datatoken address
*/
function getDatatokenAddress() external view returns (address) {
return _datatokenAddress;
}
/**
* @dev getBaseTokenAddress
* Returns the current baseToken address
*/
function getBaseTokenAddress() external view returns (address) {
return _baseTokenAddress;
}
/**
* @dev setSwapFee
* Allows controller to change the swapFee
* @param swapFee new swap fee (max 1e17 = 10 % , 1e16 = 1% , 1e15 = 0.1%, 1e14 = 0.01%)
*/
function setSwapFee(uint256 swapFee) public {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(swapFee >= MIN_FEE, "ERR_MIN_FEE");
require(swapFee <= MAX_FEE, "ERR_MAX_FEE");
_swapFee = swapFee;
emit SwapFeeChanged(msg.sender, swapFee);
}
/**
* @dev finalize
* Finalize pool. After this,new tokens cannot be bound
*/
function finalize() internal {
_finalized = true;
_publicSwap = true;
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(msg.sender, INIT_POOL_SUPPLY);
}
/**
* @dev bind
* Bind a new token to the pool.
* @param token token address
* @param balance initial reserve
* @param denorm denormalized weight
*/
function bind(
address token,
uint256 balance,
uint256 denorm
) internal {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(!_records[token].bound, "ERR_IS_BOUND");
require(!_finalized, "ERR_IS_FINALIZED");
require(_tokens.length < MAX_BOUND_TOKENS, "ERR_MAX_TOKENS");
_records[token] = Record({
bound: true,
index: _tokens.length,
denorm: 0, // balance and denorm will be validated
balance: 0 // and set by `rebind`
});
_tokens.push(token);
rebind(token, balance, denorm);
}
/**
* @dev rebind
* Update pool reserves & weight after a token bind
* @param token token address
* @param balance initial reserve
* @param denorm denormalized weight
*/
function rebind(
address token,
uint256 balance,
uint256 denorm
) internal {
require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE");
// Adjust the denorm and totalWeight
uint256 oldWeight = _records[token].denorm;
if (denorm > oldWeight) {
_totalWeight = badd(_totalWeight, bsub(denorm, oldWeight));
require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
} else if (denorm < oldWeight) {
_totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm));
}
_records[token].denorm = denorm;
// Adjust the balance record and actual token balance
uint256 oldBalance = _records[token].balance;
_records[token].balance = balance;
if (balance > oldBalance) {
_pullUnderlying(token, msg.sender, bsub(balance, oldBalance));
} else if (balance < oldBalance) {
// In this case liquidity is being withdrawn, we don't have EXIT_FEES
uint256 tokenBalanceWithdrawn = bsub(oldBalance, balance);
_pushUnderlying(
token,
msg.sender,
tokenBalanceWithdrawn
);
}
}
/**
* @dev getSpotPrice
* Return the spot price of swapping tokenIn to tokenOut
* @param tokenIn in token
* @param tokenOut out token
* @param _consumeMarketSwapFee consume market swap fee
*/
function getSpotPrice(
address tokenIn,
address tokenOut,
uint256 _consumeMarketSwapFee
) external view _viewlock_ returns (uint256 spotPrice) {
_checkBound(tokenIn);
_checkBound(tokenOut);
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return
calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_consumeMarketSwapFee
);
}
// view function used for batch buy. useful for frontend
/**
* @dev getAmountInExactOut
* How many tokensIn do you need in order to get exact tokenAmountOut.
Returns: tokenAmountIn, LPFee, opcFee , publishMarketSwapFee, consumeMarketSwapFee
* @param tokenIn token to be swaped
* @param tokenOut token to get
* @param tokenAmountOut exact amount of tokenOut
* @param _consumeMarketSwapFee consume market swap fee
*/
function getAmountInExactOut(
address tokenIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 _consumeMarketSwapFee
)
external
view
returns (
// _viewlock_
uint256 tokenAmountIn, uint lpFeeAmount,
uint oceanFeeAmount,
uint publishMarketSwapFeeAmount,
uint consumeMarketSwapFeeAmount
)
{
_checkBound(tokenIn);
_checkBound(tokenOut);
uint256[4] memory data = [
_records[tokenIn].balance,
_records[tokenIn].denorm,
_records[tokenOut].balance,
_records[tokenOut].denorm
];
uint tokenAmountInBalance;
swapfees memory _swapfees;
(tokenAmountIn, tokenAmountInBalance, _swapfees) =
calcInGivenOut(
data,
tokenAmountOut,
// tokenIn,
_consumeMarketSwapFee
);
return(tokenAmountIn, _swapfees.LPFee, _swapfees.oceanFeeAmount,
_swapfees.publishMarketFeeAmount, _swapfees.consumeMarketFee);
}
// view function useful for frontend
/**
* @dev getAmountOutExactIn
* How many tokensOut you will get for a exact tokenAmountIn
Returns: tokenAmountOut, LPFee, opcFee , publishMarketSwapFee, consumeMarketSwapFee
* @param tokenIn token to be swaped
* @param tokenOut token to get
* @param tokenAmountOut exact amount of tokenOut
* @param _consumeMarketSwapFee consume market swap fee
*/
function getAmountOutExactIn(
address tokenIn,
address tokenOut,
uint256 tokenAmountIn,
uint256 _consumeMarketSwapFee
)
external
view
returns (
// _viewlock_
uint256 tokenAmountOut,
uint lpFeeAmount,
uint oceanFeeAmount,
uint publishMarketSwapFeeAmount,
uint consumeMarketSwapFeeAmount
)
{
_checkBound(tokenIn);
_checkBound(tokenOut);
uint256[4] memory data = [
_records[tokenIn].balance,
_records[tokenIn].denorm,
_records[tokenOut].balance,
_records[tokenOut].denorm
];
uint balanceInToAdd;
swapfees memory _swapfees;
(tokenAmountOut, balanceInToAdd, _swapfees) =
calcOutGivenIn(
data,
tokenAmountIn,
// tokenIn,
_consumeMarketSwapFee
);
return(tokenAmountOut, _swapfees.LPFee,
_swapfees.oceanFeeAmount, _swapfees.publishMarketFeeAmount, _swapfees.consumeMarketFee);
}
/**
* @dev joinPool
* Adds dual side liquidity to the pool (both datatoken and basetoken)
* @param poolAmountOut expected number of pool shares that you will get
* @param maxAmountsIn array with maxium amounts spent
*/
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn)
external
_lock_
{
require(_finalized, "ERR_NOT_FINALIZED");
uint256 poolTotal = totalSupply();
uint256 ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
for (uint256 i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint256 bal = _records[t].balance;
uint256 tokenAmountIn = bmul(ratio, bal);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_records[t].balance = badd(_records[t].balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, t, tokenAmountIn, block.timestamp);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
emit LOG_BPT(poolAmountOut);
}
/**
* @dev exitPool
* Removes dual side liquidity from the pool (both datatoken and basetoken)
* @param poolAmountIn amount of pool shares spent
* @param minAmountsOut array with minimum amount of tokens expected
*/
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut)
external
_lock_
{
require(_finalized, "ERR_NOT_FINALIZED");
uint256 poolTotal = totalSupply();
//uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
//uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint256 ratio = bdiv(poolAmountIn, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
//_pushPoolShare(_factory, exitFee);
_burnPoolShare(poolAmountIn);
for (uint256 i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint256 bal = _records[t].balance;
uint256 tokenAmountOut = bmul(ratio, bal);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(_records[t].balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut, block.timestamp);
_pushUnderlying(t, msg.sender, tokenAmountOut);
}
emit LOG_BPT(poolAmountIn);
}
/**
* @dev swapExactAmountIn
* Swaps an exact amount of tokensIn to get a mimum amount of tokenOut
* @param tokenInOutMarket array of addreses: [tokenIn, tokenOut, consumeMarketFeeAddress]
* @param amountsInOutMaxFee array of ints: [tokenAmountIn, minAmountOut, maxPrice, consumeMarketSwapFee]
*/
function swapExactAmountIn(
address[3] calldata tokenInOutMarket,
uint256[4] calldata amountsInOutMaxFee
) external _lock_ returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
require(_finalized, "ERR_NOT_FINALIZED");
_checkBound(tokenInOutMarket[0]);
_checkBound(tokenInOutMarket[1]);
Record storage inRecord = _records[address(tokenInOutMarket[0])];
Record storage outRecord = _records[address(tokenInOutMarket[1])];
require(amountsInOutMaxFee[3] ==0 || amountsInOutMaxFee[3] >= MIN_FEE,'ConsumeSwapFee too low');
require(amountsInOutMaxFee[3] <= MAX_FEE,'ConsumeSwapFee too high');
require(
amountsInOutMaxFee[0] <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
amountsInOutMaxFee[3]
);
require(
spotPriceBefore <= amountsInOutMaxFee[2],
"ERR_BAD_LIMIT_PRICE"
);
uint256 balanceInToAdd;
uint256[4] memory data = [
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm
];
swapfees memory _swapfees;
(tokenAmountOut, balanceInToAdd, _swapfees) = calcOutGivenIn(
data,
amountsInOutMaxFee[0],
// tokenInOutMarket[0],
amountsInOutMaxFee[3]
);
// update balances
communityFees[tokenInOutMarket[0]] = badd(communityFees[tokenInOutMarket[0]],_swapfees.oceanFeeAmount);
publishMarketFees[tokenInOutMarket[0]] =
badd(publishMarketFees[tokenInOutMarket[0]],_swapfees.publishMarketFeeAmount);
emit SWAP_FEES(_swapfees.LPFee, _swapfees.oceanFeeAmount,
_swapfees.publishMarketFeeAmount,_swapfees.consumeMarketFee, tokenInOutMarket[0]);
require(tokenAmountOut >= amountsInOutMaxFee[1], "ERR_LIMIT_OUT");
inRecord.balance = badd(inRecord.balance, balanceInToAdd);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
amountsInOutMaxFee[3]
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= amountsInOutMaxFee[2], "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(amountsInOutMaxFee[0], tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(
msg.sender,
tokenInOutMarket[0],
tokenInOutMarket[1],
amountsInOutMaxFee[0],
tokenAmountOut,
block.timestamp
);
_pullUnderlying(tokenInOutMarket[0], msg.sender, amountsInOutMaxFee[0]);
uint256 consumeMarketFeeAmount = bsub(
amountsInOutMaxFee[0],
bmul(amountsInOutMaxFee[0], bsub(BONE, amountsInOutMaxFee[3]))
);
if (amountsInOutMaxFee[3] > 0) {
IERC20(tokenInOutMarket[0]).safeTransfer(
tokenInOutMarket[2],
consumeMarketFeeAmount
);
emit ConsumeMarketFee(
tokenInOutMarket[2],
tokenInOutMarket[0],
consumeMarketFeeAmount
);
}
_pushUnderlying(tokenInOutMarket[1], msg.sender, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter); //returning spot price 0 because there is no public spotPrice
}
/**
* @dev swapExactAmountOut
* Swaps a maximum maxAmountIn of tokensIn to get an exact amount of tokenOut
* @param tokenInOutMarket array of addreses: [tokenIn, tokenOut, consumeMarketFeeAddress]
* @param amountsInOutMaxFee array of ints: [maxAmountIn,tokenAmountOut,maxPrice, consumeMarketSwapFee]
*/
function swapExactAmountOut(
address[3] calldata tokenInOutMarket,
uint256[4] calldata amountsInOutMaxFee
) external _lock_ returns (uint256 tokenAmountIn, uint256 spotPriceAfter) {
require(_finalized, "ERR_NOT_FINALIZED");
require(amountsInOutMaxFee[3] ==0 || amountsInOutMaxFee[3] >= MIN_FEE,'ConsumeSwapFee too low');
require(amountsInOutMaxFee[3] <= MAX_FEE,'ConsumeSwapFee too high');
_checkBound(tokenInOutMarket[0]);
_checkBound(tokenInOutMarket[1]);
Record storage inRecord = _records[address(tokenInOutMarket[0])];
Record storage outRecord = _records[address(tokenInOutMarket[1])];
require(
amountsInOutMaxFee[1] <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
amountsInOutMaxFee[3]
);
require(
spotPriceBefore <= amountsInOutMaxFee[2],
"ERR_BAD_LIMIT_PRICE"
);
// this is the amount we are going to register in balances
// (only takes account of swapFee, not OPC and market fee,
//in order to not affect price during following swaps, fee wtihdrawl etc)
uint256 balanceToAdd;
uint256[4] memory data = [
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm
];
swapfees memory _swapfees;
(tokenAmountIn, balanceToAdd,
_swapfees) = calcInGivenOut(
data,
amountsInOutMaxFee[1],
//tokenInOutMarket[0],
amountsInOutMaxFee[3]
);
communityFees[tokenInOutMarket[0]] = badd(communityFees[tokenInOutMarket[0]],_swapfees.oceanFeeAmount);
publishMarketFees[tokenInOutMarket[0]]
= badd(publishMarketFees[tokenInOutMarket[0]],_swapfees.publishMarketFeeAmount);
emit SWAP_FEES(_swapfees.LPFee, _swapfees.oceanFeeAmount,
_swapfees.publishMarketFeeAmount,_swapfees.consumeMarketFee, tokenInOutMarket[0]);
require(tokenAmountIn <= amountsInOutMaxFee[0], "ERR_LIMIT_IN");
inRecord.balance = badd(inRecord.balance, balanceToAdd);
outRecord.balance = bsub(outRecord.balance, amountsInOutMaxFee[1]);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
amountsInOutMaxFee[3]
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= amountsInOutMaxFee[2], "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, amountsInOutMaxFee[1]),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(
msg.sender,
tokenInOutMarket[0],
tokenInOutMarket[1],
tokenAmountIn,
amountsInOutMaxFee[1],
block.timestamp
);
_pullUnderlying(tokenInOutMarket[0], msg.sender, tokenAmountIn);
uint256 consumeMarketFeeAmount = bsub(
tokenAmountIn,
bmul(tokenAmountIn, bsub(BONE, amountsInOutMaxFee[3]))
);
if (amountsInOutMaxFee[3] > 0) {
IERC20(tokenInOutMarket[0]).safeTransfer(
tokenInOutMarket[2],// market address
consumeMarketFeeAmount
);
emit ConsumeMarketFee(
tokenInOutMarket[2], // to (market address)
tokenInOutMarket[0], // token
consumeMarketFeeAmount
);
}
_pushUnderlying(tokenInOutMarket[1], msg.sender, amountsInOutMaxFee[1]);
return (tokenAmountIn, spotPriceAfter);
}
/**
* @dev joinswapExternAmountIn
* Single side add liquidity to the pool,
* expecting a minPoolAmountOut of shares for spending tokenAmountIn basetokens
* @param tokenAmountIn exact number of base tokens to spend
* @param minPoolAmountOut minimum of pool shares expectex
*/
function joinswapExternAmountIn(
uint256 tokenAmountIn,
uint256 minPoolAmountOut
) external _lock_ returns (uint256 poolAmountOut) {
//tokenIn = _baseTokenAddress;
require(_finalized, "ERR_NOT_FINALIZED");
_checkBound(_baseTokenAddress);
require(
tokenAmountIn <= bmul(_records[_baseTokenAddress].balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
//ask ssContract
Record storage inRecord = _records[_baseTokenAddress];
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn
);
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, _baseTokenAddress, tokenAmountIn, block.timestamp);
emit LOG_BPT(poolAmountOut);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(_baseTokenAddress, msg.sender, tokenAmountIn);
//ask the ssContract to stake as well
//calculate how much should the 1ss stake
Record storage ssInRecord = _records[_datatokenAddress];
uint256 ssAmountIn = calcSingleInGivenPoolOut(
ssInRecord.balance,
ssInRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut
);
if (ssContract.canStake(_datatokenAddress, ssAmountIn)) {
//call 1ss to approve
ssContract.Stake(_datatokenAddress, ssAmountIn);
// follow the same path
ssInRecord.balance = badd(ssInRecord.balance, ssAmountIn);
emit LOG_JOIN(
_controller,
_datatokenAddress,
ssAmountIn,
block.timestamp
);
emit LOG_BPT_SS(poolAmountOut);
_mintPoolShare(poolAmountOut);
_pushPoolShare(_controller, poolAmountOut);
_pullUnderlying(_datatokenAddress, _controller, ssAmountIn);
}
return poolAmountOut;
}
/**
* @dev exitswapPoolAmountIn
* Single side remove liquidity from the pool,
* expecting a minAmountOut of basetokens for spending poolAmountIn pool shares
* @param poolAmountIn exact number of pool shares to spend
* @param minAmountOut minimum amount of basetokens expected
*/
function exitswapPoolAmountIn(
uint256 poolAmountIn,
uint256 minAmountOut
) external _lock_ returns (uint256 tokenAmountOut) {
//tokenOut = _baseTokenAddress;
require(_finalized, "ERR_NOT_FINALIZED");
_checkBound(_baseTokenAddress);
Record storage outRecord = _records[_baseTokenAddress];
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(
tokenAmountOut <= bmul(_records[_baseTokenAddress].balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
//uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, _baseTokenAddress, tokenAmountOut, block.timestamp);
emit LOG_BPT(poolAmountIn);
_pullPoolShare(msg.sender, poolAmountIn);
//_burnPoolShare(bsub(poolAmountIn, exitFee));
_burnPoolShare(poolAmountIn);
//_pushPoolShare(_factory, exitFee);
_pushUnderlying(_baseTokenAddress, msg.sender, tokenAmountOut);
//ask the ssContract to unstake as well
//calculate how much should the 1ss unstake
if (
ssContract.canUnStake(_datatokenAddress, poolAmountIn)
) {
Record storage ssOutRecord = _records[_datatokenAddress];
uint256 ssAmountOut = calcSingleOutGivenPoolIn(
ssOutRecord.balance,
ssOutRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn
);
ssOutRecord.balance = bsub(ssOutRecord.balance, ssAmountOut);
//exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(
_controller,
_datatokenAddress,
ssAmountOut,
block.timestamp
);
_pullPoolShare(_controller, poolAmountIn);
//_burnPoolShare(bsub(poolAmountIn, exitFee));
_burnPoolShare(poolAmountIn);
//_pushPoolShare(_factory, exitFee);
_pushUnderlying(_datatokenAddress, _controller, ssAmountOut);
//call unstake on 1ss to do cleanup on their side
ssContract.UnStake(
_datatokenAddress,
ssAmountOut,
poolAmountIn
);
emit LOG_BPT_SS(poolAmountIn);
}
return tokenAmountOut;
}
/**
* @dev calcSingleOutPoolIn
* Returns expected amount of tokenOut for removing exact poolAmountIn pool shares from the pool
* @param tokenOut tokenOut
* @param poolAmountIn amount of shares spent
*/
function calcSingleOutPoolIn(address tokenOut, uint256 poolAmountIn)
external
view
returns (uint256 tokenAmountOut)
{
Record memory outRecord = _records[tokenOut];
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn
);
return tokenAmountOut;
}
/**
* @dev calcPoolInSingleOut
* Returns number of poolshares needed to withdraw exact tokenAmountOut tokens
* @param tokenOut tokenOut
* @param tokenAmountOut expected amount of tokensOut
*/
function calcPoolInSingleOut(address tokenOut, uint256 tokenAmountOut)
external
view
returns (uint256 poolAmountIn)
{
Record memory outRecord = _records[tokenOut];
poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut
);
return poolAmountIn;
}
/**
* @dev calcSingleInPoolOut
* Returns number of tokens to be staked to the pool in order to get an exact number of poolshares
* @param tokenIn tokenIn
* @param poolAmountOut expected amount of pool shares
*/
function calcSingleInPoolOut(address tokenIn, uint256 poolAmountOut)
external
view
returns (uint256 tokenAmountIn)
{
Record memory inRecord = _records[tokenIn];
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut
);
return tokenAmountIn;
}
/**
* @dev calcPoolOutSingleIn
* Returns number of poolshares obtain by staking exact tokenAmountIn tokens
* @param tokenIn tokenIn
* @param tokenAmountIn exact number of tokens staked
*/
function calcPoolOutSingleIn(address tokenIn, uint256 tokenAmountIn)
external
view
returns (uint256 poolAmountOut)
{
Record memory inRecord = _records[tokenIn];
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn
);
return poolAmountOut;
}
// Internal functions below
// ==
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(
address erc20,
address from,
uint256 amount
) internal {
uint256 balanceBefore = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).safeTransferFrom(from, address(this), amount);
require(IERC20(erc20).balanceOf(address(this)) >= balanceBefore + amount,
"Transfer amount is too low");
//require(xfer, "ERR_ERC20_FALSE");
}
function _pushUnderlying(
address erc20,
address to,
uint256 amount
) internal {
IERC20(erc20).safeTransfer(to, amount);
//require(xfer, "ERR_ERC20_FALSE");
}
function _pullPoolShare(address from, uint256 amount) internal {
_pull(from, amount);
}
function _pushPoolShare(address to, uint256 amount) internal {
_push(to, amount);
}
function _mintPoolShare(uint256 amount) internal {
_mint(amount);
}
function _burnPoolShare(uint256 amount) internal {
_burn(amount);
}
}
|
getNumTokens Returns number of tokens bounded to pool/
|
function getNumTokens() external view returns (uint256) {
return _tokens.length;
}
| 15,821,343
|
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.4;
contract Proxy {
address implementation;
event RECEIVED369(uint indexed value, address indexed sender, bytes data); //inject NONSTANDARD NAMING
constructor(address _implementation) public {
implementation = _implementation;
}
function() external payable {
if (msg.data.length == 0 && msg.value > 0) {
emit RECEIVED369(msg.value, msg.sender, msg.data);
} else {
// solium-disable-next-line security/no-inline-assembly
assembly {
let target := sload(0)
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas, target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
contract BaseWallet {
function INIT685(address _owner, address[] calldata _modules) external; //inject NONSTANDARD NAMING
function AUTHORISEMODULE812(address _module, bool _value) external; //inject NONSTANDARD NAMING
function ENABLESTATICCALL186(address _module, bytes4 _method) external; //inject NONSTANDARD NAMING
function SETOWNER798(address _newOwner) external; //inject NONSTANDARD NAMING
function INVOKE21(address _target, uint _value, bytes calldata _data) external returns (bytes memory _result); //inject NONSTANDARD NAMING
function() external payable;
}
contract Owned {
// The owner
address public owner;
event OWNERCHANGED436(address indexed _newOwner); //inject NONSTANDARD NAMING
modifier ONLYOWNER47 { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
function CHANGEOWNER39(address _newOwner) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OWNERCHANGED436(_newOwner);
}
}
contract Managed is Owned {
// The managers
mapping (address => bool) public managers;
modifier ONLYMANAGER653 { //inject NONSTANDARD NAMING
require(managers[msg.sender] == true, "M: Must be manager");
_;
}
event MANAGERADDED439(address indexed _manager); //inject NONSTANDARD NAMING
event MANAGERREVOKED398(address indexed _manager); //inject NONSTANDARD NAMING
function ADDMANAGER871(address _manager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_manager != address(0), "M: Address must not be null");
if (managers[_manager] == false) {
managers[_manager] = true;
emit MANAGERADDED439(_manager);
}
}
function REVOKEMANAGER965(address _manager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(managers[_manager] == true, "M: Target must be an existing manager");
delete managers[_manager];
emit MANAGERREVOKED398(_manager);
}
}
interface IENSManager {
event ROOTNODEOWNERCHANGE990(bytes32 indexed _rootnode, address indexed _newOwner); //inject NONSTANDARD NAMING
event ENSRESOLVERCHANGED200(address addr); //inject NONSTANDARD NAMING
event REGISTERED245(address indexed _owner, string _ens); //inject NONSTANDARD NAMING
event UNREGISTERED914(string _ens); //inject NONSTANDARD NAMING
function CHANGEROOTNODEOWNER398(address _newOwner) external; //inject NONSTANDARD NAMING
function REGISTER194(string calldata _label, address _owner) external; //inject NONSTANDARD NAMING
function ISAVAILABLE666(bytes32 _subnode) external view returns(bool); //inject NONSTANDARD NAMING
function GETENSREVERSEREGISTRAR478() external view returns (address); //inject NONSTANDARD NAMING
function ENSRESOLVER758() external view returns (address); //inject NONSTANDARD NAMING
}
contract ModuleRegistry {
function REGISTERMODULE445(address _module, bytes32 _name) external; //inject NONSTANDARD NAMING
function DEREGISTERMODULE847(address _module) external; //inject NONSTANDARD NAMING
function REGISTERUPGRADER868(address _upgrader, bytes32 _name) external; //inject NONSTANDARD NAMING
function DEREGISTERUPGRADER19(address _upgrader) external; //inject NONSTANDARD NAMING
function MODULEINFO202(address _module) external view returns (bytes32); //inject NONSTANDARD NAMING
function UPGRADERINFO731(address _upgrader) external view returns (bytes32); //inject NONSTANDARD NAMING
function ISREGISTEREDMODULE404(address _module) external view returns (bool); //inject NONSTANDARD NAMING
function ISREGISTEREDMODULE404(address[] calldata _modules) external view returns (bool); //inject NONSTANDARD NAMING
function ISREGISTEREDUPGRADER426(address _upgrader) external view returns (bool); //inject NONSTANDARD NAMING
}
interface IGuardianStorage{
function ADDGUARDIAN190(BaseWallet _wallet, address _guardian) external; //inject NONSTANDARD NAMING
function REVOKEGUARDIAN58(BaseWallet _wallet, address _guardian) external; //inject NONSTANDARD NAMING
function ISGUARDIAN756(BaseWallet _wallet, address _guardian) external view returns (bool); //inject NONSTANDARD NAMING
}
contract WalletFactory is Owned, Managed {
// The address of the module dregistry
address public moduleRegistry;
// The address of the base wallet implementation
address public walletImplementation;
// The address of the ENS manager
address public ensManager;
// The address of the GuardianStorage
address public guardianStorage;
// *************** Events *************************** //
event MODULEREGISTRYCHANGED334(address addr); //inject NONSTANDARD NAMING
event ENSMANAGERCHANGED648(address addr); //inject NONSTANDARD NAMING
event GUARDIANSTORAGECHANGED398(address addr); //inject NONSTANDARD NAMING
event WALLETCREATED189(address indexed wallet, address indexed owner, address indexed guardian); //inject NONSTANDARD NAMING
// *************** Modifiers *************************** //
modifier GUARDIANSTORAGEDEFINED740 { //inject NONSTANDARD NAMING
require(guardianStorage != address(0), "GuardianStorage address not defined");
_;
}
// *************** Constructor ********************** //
constructor(address _moduleRegistry, address _walletImplementation, address _ensManager) public {
moduleRegistry = _moduleRegistry;
walletImplementation = _walletImplementation;
ensManager = _ensManager;
}
// *************** External Functions ********************* //
function CREATEWALLET541( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label
)
external
ONLYMANAGER653
{
_CREATEWALLET379(_owner, _modules, _label, address(0));
}
function CREATEWALLETWITHGUARDIAN388( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
address _guardian
)
external
ONLYMANAGER653
GUARDIANSTORAGEDEFINED740
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_CREATEWALLET379(_owner, _modules, _label, _guardian);
}
function CREATECOUNTERFACTUALWALLET430( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
bytes32 _salt
)
external
ONLYMANAGER653
{
_CREATECOUNTERFACTUALWALLET436(_owner, _modules, _label, address(0), _salt);
}
function CREATECOUNTERFACTUALWALLETWITHGUARDIAN167( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
address _guardian,
bytes32 _salt
)
external
ONLYMANAGER653
GUARDIANSTORAGEDEFINED740
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_CREATECOUNTERFACTUALWALLET436(_owner, _modules, _label, _guardian, _salt);
}
function GETADDRESSFORCOUNTERFACTUALWALLET140( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
bytes32 _salt
)
external
view
returns (address _wallet)
{
_wallet = _GETADDRESSFORCOUNTERFACTUALWALLET709(_owner, _modules, address(0), _salt);
}
function GETADDRESSFORCOUNTERFACTUALWALLETWITHGUARDIAN758( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
address _guardian,
bytes32 _salt
)
external
view
returns (address _wallet)
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_wallet = _GETADDRESSFORCOUNTERFACTUALWALLET709(_owner, _modules, _guardian, _salt);
}
function CHANGEMODULEREGISTRY647(address _moduleRegistry) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_moduleRegistry != address(0), "WF: address cannot be null");
moduleRegistry = _moduleRegistry;
emit MODULEREGISTRYCHANGED334(_moduleRegistry);
}
function CHANGEENSMANAGER916(address _ensManager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_ensManager != address(0), "WF: address cannot be null");
ensManager = _ensManager;
emit ENSMANAGERCHANGED648(_ensManager);
}
function CHANGEGUARDIANSTORAGE66(address _guardianStorage) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_guardianStorage != address(0), "WF: address cannot be null");
guardianStorage = _guardianStorage;
emit GUARDIANSTORAGECHANGED398(_guardianStorage);
}
function INIT685(BaseWallet _wallet) external pure { // solium-disable-line no-empty-blocks //inject NONSTANDARD NAMING
//do nothing
}
// *************** Internal Functions ********************* //
function _CREATEWALLET379(address _owner, address[] memory _modules, string memory _label, address _guardian) internal { //inject NONSTANDARD NAMING
_VALIDATEINPUTS330(_owner, _modules, _label);
Proxy proxy = new Proxy(walletImplementation);
address payable wallet = address(proxy);
_CONFIGUREWALLET163(BaseWallet(wallet), _owner, _modules, _label, _guardian);
}
function _CREATECOUNTERFACTUALWALLET436( //inject NONSTANDARD NAMING
address _owner,
address[] memory _modules,
string memory _label,
address _guardian,
bytes32 _salt
)
internal
{
_VALIDATEINPUTS330(_owner, _modules, _label);
bytes32 newsalt = _NEWSALT377(_salt, _owner, _modules, _guardian);
bytes memory code = abi.encodePacked(type(Proxy).creationCode, uint256(walletImplementation));
address payable wallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
wallet := create2(0, add(code, 0x20), mload(code), newsalt)
if iszero(extcodesize(wallet)) { revert(0, returndatasize) }
}
_CONFIGUREWALLET163(BaseWallet(wallet), _owner, _modules, _label, _guardian);
}
function _CONFIGUREWALLET163( //inject NONSTANDARD NAMING
BaseWallet _wallet,
address _owner,
address[] memory _modules,
string memory _label,
address _guardian
)
internal
{
// add the factory to modules so it can claim the reverse ENS or add a guardian
address[] memory extendedModules = new address[](_modules.length + 1);
extendedModules[0] = address(this);
for (uint i = 0; i < _modules.length; i++) {
extendedModules[i + 1] = _modules[i];
}
// initialise the wallet with the owner and the extended modules
_wallet.INIT685(_owner, extendedModules);
// add guardian if needed
if (_guardian != address(0)) {
IGuardianStorage(guardianStorage).ADDGUARDIAN190(_wallet, _guardian);
}
// register ENS
_REGISTERWALLETENS735(address(_wallet), _label);
// remove the factory from the authorised modules
_wallet.AUTHORISEMODULE812(address(this), false);
// emit event
emit WALLETCREATED189(address(_wallet), _owner, _guardian);
}
function _GETADDRESSFORCOUNTERFACTUALWALLET709( //inject NONSTANDARD NAMING
address _owner,
address[] memory _modules,
address _guardian,
bytes32 _salt
)
internal
view
returns (address _wallet)
{
bytes32 newsalt = _NEWSALT377(_salt, _owner, _modules, _guardian);
bytes memory code = abi.encodePacked(type(Proxy).creationCode, uint256(walletImplementation));
bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));
_wallet = address(uint160(uint256(hash)));
}
function _NEWSALT377(bytes32 _salt, address _owner, address[] memory _modules, address _guardian) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
if (_guardian == address(0)) {
return keccak256(abi.encodePacked(_salt, _owner, _modules));
} else {
return keccak256(abi.encodePacked(_salt, _owner, _modules, _guardian));
}
}
function _VALIDATEINPUTS330(address _owner, address[] memory _modules, string memory _label) internal view { //inject NONSTANDARD NAMING
require(_owner != address(0), "WF: owner cannot be null");
require(_modules.length > 0, "WF: cannot assign with less than 1 module");
require(ModuleRegistry(moduleRegistry).ISREGISTEREDMODULE404(_modules), "WF: one or more modules are not registered");
bytes memory labelBytes = bytes(_label);
require(labelBytes.length != 0, "WF: ENS lable must be defined");
}
function _REGISTERWALLETENS735(address payable _wallet, string memory _label) internal { //inject NONSTANDARD NAMING
// claim reverse
address ensResolver = IENSManager(ensManager).ENSRESOLVER758();
bytes memory methodData = abi.encodeWithSignature("claimWithResolver(address,address)", ensManager, ensResolver);
address ensReverseRegistrar = IENSManager(ensManager).GETENSREVERSEREGISTRAR478();
BaseWallet(_wallet).INVOKE21(ensReverseRegistrar, 0, methodData);
// register with ENS manager
IENSManager(ensManager).REGISTER194(_label, _wallet);
}
}
|
inject NONSTANDARD NAMING
|
function CHANGEOWNER39(address _newOwner) external ONLYOWNER47 {
| 2,513,348
|
/**
*Submitted for verification at Etherscan.io on 2022-02-25
*/
/*
* NOVA.audio - Music NFT Marketplace
* Sing a different tune!
*
* Website: www.nova.audio
* Telegram: www.t.me/novapreverify
*
*** Tokenomics ***
* 1.000.000.000 (one billion) NOVA Tokens
* Default Buy Tax: 4% (1% liquidity, 3% marketing and development)
* Default Sell Tax: 8% (1% liquidity, 7% marketing and development)
* Taxes will be abandoned after the NOVA platform release
*** Bot and Whale Protection ***
* 0.5% Max tx
* 1.5% Max wallet
* 30 Second cooldown between buys
* First three block buys are automatically blacklisted
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function 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 IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
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;
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
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;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 9;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
contract NOVA is ERC20, Ownable {
using SafeMath for uint256;
address public constant DEAD_ADDRESS = address(0xdead);
IUniswapV2Router02 public constant uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 public buyLiquidityFee = 1;
uint256 public sellLiquidityFee = 1;
uint256 public buyTxFee = 3;
uint256 public sellTxFee = 7;
uint256 public defaultSellLiquidityFee = 1;
uint256 public defaultSellTxFee = 7;
uint256 public tokensForLiquidity;
uint256 public tokensForTax;
uint256 public _tTotal = 10**9 * 10**9; // 1 billion
uint256 public swapAtAmount = _tTotal.mul(50).div(10000); // 0.10% of total supply
uint256 public maxTxLimit = _tTotal; // 0.5% of total supply set in open trading
uint256 public maxWalletLimit = _tTotal; // 1% of total supply set in open trading
address private dev;
address private liquidity;
address public uniswapV2Pair;
uint256 public launchBlock;
bool private swapping;
bool public isLaunched;
bool private cooldownEnabled = false;
bool private useBuyMap = true;
// exclude from fees
mapping (address => bool) public isExcludedFromFees;
// exclude from max transaction amount
mapping (address => bool) public isExcludedFromTxLimit;
// exclude from max wallet limit
mapping (address => bool) public isExcludedFromWalletLimit;
// if the account is blacklisted from transacting
mapping (address => bool) public isBlacklisted;
// buy map for timed sell tax
mapping (address => uint256) public _buyMap;
// mapping for cooldown
mapping (address => uint) public cooldown;
constructor() public ERC20("NOVA", "NOVA") {
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
_approve(address(this), address(uniswapV2Router), type(uint256).max);
// exclude from fees, wallet limit and transaction limit
excludeFromAllLimits(owner(), true);
excludeFromAllLimits(address(this), true);
excludeFromWalletLimit(uniswapV2Pair, true);
dev = payable(0x3b2510869a7c0829293C071beA347Cf5F95CC25f);
liquidity = payable(0x3b2510869a7c0829293C071beA347Cf5F95CC25f);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), _tTotal);
}
function excludeFromFees(address account, bool value) public onlyOwner() {
require(isExcludedFromFees[account] != value, "Fees: Already set to this value");
isExcludedFromFees[account] = value;
}
function excludeFromTxLimit(address account, bool value) public onlyOwner() {
require(isExcludedFromTxLimit[account] != value, "TxLimit: Already set to this value");
isExcludedFromTxLimit[account] = value;
}
function excludeFromWalletLimit(address account, bool value) public onlyOwner() {
require(isExcludedFromWalletLimit[account] != value, "WalletLimit: Already set to this value");
isExcludedFromWalletLimit[account] = value;
}
function excludeFromAllLimits(address account, bool value) public onlyOwner() {
excludeFromFees(account, value);
excludeFromTxLimit(account, value);
excludeFromWalletLimit(account, value);
}
function setBuyFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() {
require(liquidityFee.add(txFee) <= 4, "Total buy fee can not be more than 4%");
buyLiquidityFee = liquidityFee;
buyTxFee = txFee;
}
function setSellFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() {
require(liquidityFee.add(txFee) <= 8, "Total sell fee can not be more than 8%");
sellLiquidityFee = liquidityFee;
sellTxFee = txFee;
defaultSellLiquidityFee = liquidityFee;
defaultSellTxFee = txFee;
}
function setCooldownEnabled(bool _enabled) external onlyOwner() {
cooldownEnabled = _enabled;
}
function setUseBuyMap(bool _enabled) external onlyOwner() {
useBuyMap = _enabled;
}
function setMaxTxLimit(uint256 newLimit) external onlyOwner() {
require(newLimit > 0, "Max tx can not be 0");
maxTxLimit = newLimit * (10**9);
}
function setMaxWalletLimit(uint256 newLimit) external onlyOwner() {
require(newLimit > 0, "Max wallet can not be 0");
maxWalletLimit = newLimit * (10**9);
}
function setSwapAtAmount(uint256 amountToSwap) external onlyOwner() {
swapAtAmount = amountToSwap * (10**9);
}
function updateDevWallet(address newWallet) external onlyOwner() {
dev = newWallet;
}
function updateLiqWallet(address newWallet) external onlyOwner() {
liquidity = newWallet;
}
function addBlacklist(address account) external onlyOwner() {
require(!isBlacklisted[account], "Blacklist: Already blacklisted");
require(account != uniswapV2Pair, "Cannot blacklist pair");
_setBlacklist(account, true);
}
function removeBlacklist(address account) external onlyOwner() {
require(isBlacklisted[account], "Blacklist: Not blacklisted");
_setBlacklist(account, false);
}
function manualswap() external onlyOwner() {
uint256 totalTokensForFee = tokensForLiquidity + tokensForTax;
swapBack(totalTokensForFee);
}
function manualsend() external onlyOwner(){
uint256 contractETHBalance = address(this).balance;
payable(address(dev)).transfer(contractETHBalance);
}
function openTrading() external onlyOwner() {
require(!isLaunched, "Contract is already launched");
isLaunched = true;
launchBlock = block.number;
cooldownEnabled = true;
maxTxLimit = _tTotal.mul(50).div(10000);
maxWalletLimit = _tTotal.mul(100).div(10000);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "transfer from the zero address");
require(to != address(0), "transfer to the zero address");
require(amount <= maxTxLimit || isExcludedFromTxLimit[from] || isExcludedFromTxLimit[to], "Tx Amount too large");
require(balanceOf(to).add(amount) <= maxWalletLimit || isExcludedFromWalletLimit[to], "Transfer will exceed wallet limit");
require(isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to], "Waiting to go live");
require(!isBlacklisted[from], "Sender is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 totalTokensForFee = tokensForLiquidity + tokensForTax;
bool canSwap = totalTokensForFee >= swapAtAmount;
if(
from != uniswapV2Pair &&
canSwap &&
!swapping
) {
swapping = true;
swapBack(totalTokensForFee);
swapping = false;
} else if(
from == uniswapV2Pair &&
to != uniswapV2Pair &&
block.number < launchBlock + 3 &&
!isExcludedFromFees[to]
) {
_setBlacklist(to, true);
}
bool takeFee = !swapping;
if(isExcludedFromFees[from] || isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
uint256 fees;
// Sell Fees
if (to == uniswapV2Pair) {
sellLiquidityFee = defaultSellLiquidityFee;
sellTxFee = defaultSellTxFee;
uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee);
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(fees.mul(sellLiquidityFee).div(sellTotalFees));
tokensForTax = tokensForTax.add(fees.mul(sellTxFee).div(sellTotalFees));
}
// Buy & Transfer Fees
else {
if(cooldownEnabled){
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (useBuyMap && _buyMap[to] == 0) {
_buyMap[to] = block.timestamp;
}
uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee);
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(fees.mul(buyLiquidityFee).div(buyTotalFees));
tokensForTax = tokensForTax.add(fees.mul(buyTxFee).div(buyTotalFees));
}
if(fees > 0){
super._transfer(from, address(this), fees);
amount = amount.sub(fees);
}
}
super._transfer(from, to, amount);
}
function swapBack(uint256 totalTokensForFee) private {
uint256 toSwap = swapAtAmount;
// Halve the amount of liquidity tokens
uint256 liquidityTokens = toSwap.mul(tokensForLiquidity).div(totalTokensForFee).div(2);
uint256 taxTokens = toSwap.sub(liquidityTokens).sub(liquidityTokens);
uint256 amountToSwapForETH = toSwap.sub(liquidityTokens);
_swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance;
uint256 ethForTax = ethBalance.mul(taxTokens).div(amountToSwapForETH);
uint256 ethForLiquidity = ethBalance.sub(ethForTax);
tokensForLiquidity = tokensForLiquidity.sub(liquidityTokens.mul(2));
tokensForTax = tokensForTax.sub(toSwap.sub(liquidityTokens.mul(2)));
payable(address(dev)).transfer(ethForTax);
_addLiquidity(liquidityTokens, ethForLiquidity);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
liquidity,
block.timestamp
);
}
function _swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function _setBlacklist(address account, bool value) internal {
isBlacklisted[account] = value;
}
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent){
require(_token != address(this), "Can't withdraw native tokens");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
}
receive() external payable {}
}
|
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);
}
| 8,074,730
|
pragma solidity 0.4.24;
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
contract ERC721Basic is ERC165 {
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
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract Governable {
event Pause();
event Unpause();
address public governor;
bool public paused = false;
constructor() public {
governor = msg.sender;
}
function setGovernor(address _gov) public onlyGovernor {
governor = _gov;
}
modifier onlyGovernor {
require(msg.sender == governor);
_;
}
/**
* @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() onlyGovernor whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyGovernor whenPaused public {
paused = false;
emit Unpause();
}
}
contract CardBase is Governable {
struct Card {
uint16 proto;
uint16 purity;
}
function getCard(uint id) public view returns (uint16 proto, uint16 purity) {
Card memory card = cards[id];
return (card.proto, card.purity);
}
function getShine(uint16 purity) public pure returns (uint8) {
return uint8(purity / 1000);
}
Card[] public cards;
}
contract CardProto is CardBase {
event NewProtoCard(
uint16 id, uint8 season, uint8 god,
Rarity rarity, uint8 mana, uint8 attack,
uint8 health, uint8 cardType, uint8 tribe, bool packable
);
struct Limit {
uint64 limit;
bool exists;
}
// limits for mythic cards
mapping(uint16 => Limit) public limits;
// can only set limits once
function setLimit(uint16 id, uint64 limit) public onlyGovernor {
Limit memory l = limits[id];
require(!l.exists);
limits[id] = Limit({
limit: limit,
exists: true
});
}
function getLimit(uint16 id) public view returns (uint64 limit, bool set) {
Limit memory l = limits[id];
return (l.limit, l.exists);
}
// could make these arrays to save gas
// not really necessary - will be update a very limited no of times
mapping(uint8 => bool) public seasonTradable;
mapping(uint8 => bool) public seasonTradabilityLocked;
uint8 public currentSeason;
function makeTradable(uint8 season) public onlyGovernor {
seasonTradable[season] = true;
}
function makeUntradable(uint8 season) public onlyGovernor {
require(!seasonTradabilityLocked[season]);
seasonTradable[season] = false;
}
function makePermanantlyTradable(uint8 season) public onlyGovernor {
require(seasonTradable[season]);
seasonTradabilityLocked[season] = true;
}
function isTradable(uint16 proto) public view returns (bool) {
return seasonTradable[protos[proto].season];
}
function nextSeason() public onlyGovernor {
//Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M
require(currentSeason <= 255);
currentSeason++;
mythic.length = 0;
legendary.length = 0;
epic.length = 0;
rare.length = 0;
common.length = 0;
}
enum Rarity {
Common,
Rare,
Epic,
Legendary,
Mythic
}
uint8 constant SPELL = 1;
uint8 constant MINION = 2;
uint8 constant WEAPON = 3;
uint8 constant HERO = 4;
struct ProtoCard {
bool exists;
uint8 god;
uint8 season;
uint8 cardType;
Rarity rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
// there is a particular design decision driving this:
// need to be able to iterate over mythics only for card generation
// don't store 5 different arrays: have to use 2 ids
// better to bear this cost (2 bytes per proto card)
// rather than 1 byte per instance
uint16 public protoCount;
mapping(uint16 => ProtoCard) protos;
uint16[] public mythic;
uint16[] public legendary;
uint16[] public epic;
uint16[] public rare;
uint16[] public common;
function addProtos(
uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks,
uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable
) public onlyGovernor returns(uint16) {
for (uint i = 0; i < externalIDs.length; i++) {
ProtoCard memory card = ProtoCard({
exists: true,
god: gods[i],
season: currentSeason,
cardType: cardTypes[i],
rarity: rarities[i],
mana: manas[i],
attack: attacks[i],
health: healths[i],
tribe: tribes[i]
});
_addProto(externalIDs[i], card, packable[i]);
}
}
function addProto(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: cardType,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function addWeapon(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: WEAPON,
rarity: rarity,
mana: mana,
attack: attack,
health: durability,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: SPELL,
rarity: rarity,
mana: mana,
attack: 0,
health: 0,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addMinion(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: MINION,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal {
require(!protos[externalID].exists);
card.exists = true;
protos[externalID] = card;
protoCount++;
emit NewProtoCard(
externalID, currentSeason, card.god,
card.rarity, card.mana, card.attack,
card.health, card.cardType, card.tribe, packable
);
if (packable) {
Rarity rarity = card.rarity;
if (rarity == Rarity.Common) {
common.push(externalID);
} else if (rarity == Rarity.Rare) {
rare.push(externalID);
} else if (rarity == Rarity.Epic) {
epic.push(externalID);
} else if (rarity == Rarity.Legendary) {
legendary.push(externalID);
} else if (rarity == Rarity.Mythic) {
mythic.push(externalID);
} else {
require(false);
}
}
}
function getProto(uint16 id) public view returns(
bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) {
ProtoCard memory proto = protos[id];
return (
proto.exists,
proto.god,
proto.season,
proto.cardType,
proto.rarity,
proto.mana,
proto.attack,
proto.health,
proto.tribe
);
}
function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) {
// modulo bias is fine - creates rarity tiers etc
// will obviously revert is there are no cards of that type: this is expected - should never happen
if (rarity == Rarity.Common) {
return common[random % common.length];
} else if (rarity == Rarity.Rare) {
return rare[random % rare.length];
} else if (rarity == Rarity.Epic) {
return epic[random % epic.length];
} else if (rarity == Rarity.Legendary) {
return legendary[random % legendary.length];
} else if (rarity == Rarity.Mythic) {
// make sure a mythic is available
uint16 id;
uint64 limit;
bool set;
for (uint i = 0; i < mythic.length; i++) {
id = mythic[(random + i) % mythic.length];
(limit, set) = getLimit(id);
if (set && limit > 0){
return id;
}
}
// if not, they get a legendary :(
return legendary[random % legendary.length];
}
require(false);
return 0;
}
// can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity
function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor {
ProtoCard memory pc = protos[index];
require(!seasonTradable[pc.season]);
protos[index] = ProtoCard({
exists: true,
god: god,
season: pc.season,
cardType: cardType,
rarity: pc.rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
}
}
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. 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 transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
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 ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
// mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256);
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addNewTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function addNewTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
// ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
// ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
using Strings for string;
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/*** Constants ***/
// Configure these for your own deployment
string public constant NAME = "Gods Unchained";
string public constant SYMBOL = "GODS";
string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/";
// Mapping from owner to list of owned token IDs
// EDITED: limit to 2^40 (around 1T)
mapping(address => uint40[]) internal ownedTokens;
uint32[] ownedTokensIndex;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return NAME;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return SYMBOL;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId)
);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return cards.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return _index;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
// EDITED: prevent overflow
require(length == uint32(length));
ownedTokens[_to].push(uint40(_tokenId));
ownedTokensIndex[_tokenId] = uint32(length);
}
// EDITED
// have to have in order to use array rather than mapping
function addNewTokenTo(address _to, uint256 _tokenId) internal {
super.addNewTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
// EDITED: prevent overflow
require(length == uint32(length));
ownedTokens[_to].push(uint40(_tokenId));
ownedTokensIndex.push(uint32(length));
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint32 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint40 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Gets the balance of the specified address - overrriden from previous to save gas
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
return ownedTokens[_owner].length;
}
}
contract CardOwnershipTwo is ERC721Token {
uint public burnCount;
function getActiveCards() public view returns (uint) {
return totalSupply() - burnCount;
}
/**
* @param to : the address to which the card will be transferred
* @param id : the id of the card to be transferred
*/
function transfer(address to, uint id) public payable onlyOwnerOf(id) {
require(isTradable(cards[id].proto));
require(to != address(0));
_transfer(msg.sender, to, id);
}
function _transfer(address from, address to, uint id) internal {
clearApproval(from, id);
removeTokenFrom(from, id);
addTokenTo(to, id);
emit Transfer(from, to, id);
}
/**
* @param to : the address to which the cards will be transferred
* @param ids : the ids of the cards to be transferred
*/
function transferAll(address to, uint[] ids) public payable {
for (uint i = 0; i < ids.length; i++) {
transfer(to, ids[i]);
}
}
/**
* @param proposed : the claimed owner of the cards
* @param ids : the ids of the cards to check
* @return whether proposed owns all of the cards
*/
function ownsAll(address proposed, uint[] ids) public view returns (bool) {
require(ids.length > 0);
for (uint i = 0; i < ids.length; i++) {
if (!owns(proposed, ids[i])) {
return false;
}
}
return true;
}
/**
* @param proposed : the claimed owner of the card
* @param id : the id of the card to check
* @return whether proposed owns the card
*/
function owns(address proposed, uint id) public view returns (bool) {
return ownerOf(id) == proposed;
}
function burn(uint id) public onlyOwnerOf(id) {
burnCount++;
_burn(msg.sender, id);
}
/**
* @param ids : the indices of the tokens to burn
*/
function burnAll(uint[] ids) public {
for (uint i = 0; i < ids.length; i++){
burn(ids[i]);
}
}
/**
* @param to : the address to approve for transfer
* @param id : the index of the card to be approved
*/
function approve(address to, uint id) public {
require(isTradable(cards[id].proto));
super.approve(to, id);
}
/**
* @param to : the address to approve for transfer
* @param ids : the indices of the cards to be approved
*/
function approveAll(address to, uint[] ids) public {
for (uint i = 0; i < ids.length; i++) {
approve(to, ids[i]);
}
}
/**
* @param to : the address to which the token should be transferred
* @param id : the index of the token to transfer
*/
function transferFrom(address from, address to, uint id) public {
require(isTradable(cards[id].proto));
super.transferFrom(from, to, id);
}
/**
* @param to : the address to which the tokens should be transferred
* @param ids : the indices of the tokens to transfer
*/
function transferAllFrom(address from, address to, uint[] ids) public {
for (uint i = 0; i < ids.length; i++) {
transferFrom(from, to, ids[i]);
}
}
/**
* @return the number of cards which have been burned
*/
function getBurnCount() public view returns (uint) {
return burnCount;
}
}
contract CardIntegrationTwo is CardOwnershipTwo {
address[] public packs;
event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner);
function addPack(address approved) public onlyGovernor {
packs.push(approved);
}
modifier onlyApprovedPacks {
require(_isApprovedPack());
_;
}
function _isApprovedPack() private view returns (bool) {
for (uint i = 0; i < packs.length; i++) {
if (msg.sender == address(packs[i])) {
return true;
}
}
return false;
}
function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) {
ProtoCard memory card = protos[proto];
require(card.season == currentSeason);
if (card.rarity == Rarity.Mythic) {
uint64 limit;
bool exists;
(limit, exists) = getLimit(proto);
require(!exists || limit > 0);
limits[proto].limit--;
}
return _createCard(owner, proto, purity);
}
function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) {
Card memory card = Card({
proto: proto,
purity: purity
});
uint id = cards.push(card) - 1;
_mint(owner, id);
emit CardCreated(id, proto, purity, owner);
return id;
}
/*function combineCards(uint[] ids) public whenNotPaused {
require(ids.length == 5);
require(ownsAll(msg.sender, ids));
Card memory first = cards[ids[0]];
uint16 proto = first.proto;
uint8 shine = _getShine(first.purity);
require(shine < shineLimit);
uint16 puritySum = first.purity - (shine * 1000);
burn(ids[0]);
for (uint i = 1; i < ids.length; i++) {
Card memory next = cards[ids[i]];
require(next.proto == proto);
require(_getShine(next.purity) == shine);
puritySum += (next.purity - (shine * 1000));
burn(ids[i]);
}
uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length));
_createCard(msg.sender, proto, newPurity);
}*/
// PURITY NOTES
// currently, we only
// however, to protect rarity, you'll never be abl
// this is enforced by the restriction in the create-card function
// no cards above this point can be found in packs
}
contract PreviousInterface {
function ownerOf(uint id) public view returns (address);
function getCard(uint id) public view returns (uint16, uint16);
function totalSupply() public view returns (uint);
function burnCount() public view returns (uint);
}
contract CardMigration is CardIntegrationTwo {
constructor(PreviousInterface previous) public {
old = previous;
}
// use interface to lower deployment cost
PreviousInterface old;
mapping(uint => bool) public migrated;
function migrate(uint id) public {
require(!migrated[id]);
migrated[id] = true;
address owner = old.ownerOf(id);
uint16 proto;
uint16 purity;
(proto, purity) = old.getCard(id);
_createCard(owner, proto, purity);
}
function migrateAll(uint[] ids) public {
for (uint i = 0; i < ids.length; i++){
migrate(ids[i]);
}
}
}
|
Gets the token ID at a given index of all the tokens in this contract Reverts if the index is greater or equal to the total number of tokens _index uint256 representing the index to be accessed of the tokens list return uint256 token ID at the given index of the tokens list/
|
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return _index;
}
| 6,500,521
|
pragma solidity 0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b7b2a5b693b2b8bcbeb1b2fdb0bcbe">[email protected]</a>
// released under Apache 2.0 licence
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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 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 ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract Relay is Ownable {
address public licenseSalesContractAddress;
address public registryContractAddress;
address public apiRegistryContractAddress;
address public apiCallsContractAddress;
uint public version;
// ------------------------------------------------------------------------
// Constructor, establishes ownership because contract is owned
// ------------------------------------------------------------------------
constructor() public {
version = 4;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens (just in case)
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Sets the license sales contract address
// ------------------------------------------------------------------------
function setLicenseSalesContractAddress(address newAddress) public onlyOwner {
require(newAddress != address(0));
licenseSalesContractAddress = newAddress;
}
// ------------------------------------------------------------------------
// Sets the registry contract address
// ------------------------------------------------------------------------
function setRegistryContractAddress(address newAddress) public onlyOwner {
require(newAddress != address(0));
registryContractAddress = newAddress;
}
// ------------------------------------------------------------------------
// Sets the api registry contract address
// ------------------------------------------------------------------------
function setApiRegistryContractAddress(address newAddress) public onlyOwner {
require(newAddress != address(0));
apiRegistryContractAddress = newAddress;
}
// ------------------------------------------------------------------------
// Sets the api calls contract address
// ------------------------------------------------------------------------
function setApiCallsContractAddress(address newAddress) public onlyOwner {
require(newAddress != address(0));
apiCallsContractAddress = newAddress;
}
}
contract APIRegistry is Ownable {
struct APIForSale {
uint pricePerCall;
bytes32 sellerUsername;
bytes32 apiName;
address sellerAddress;
string hostname;
string docsUrl;
}
mapping(string => uint) internal apiIds;
mapping(uint => APIForSale) public apis;
uint public numApis;
uint public version;
// ------------------------------------------------------------------------
// Constructor, establishes ownership because contract is owned
// ------------------------------------------------------------------------
constructor() public {
numApis = 0;
version = 1;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens (just in case)
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Lets a user list an API to sell
// ------------------------------------------------------------------------
function listApi(uint pricePerCall, bytes32 sellerUsername, bytes32 apiName, string hostname, string docsUrl) public {
// make sure input params are valid
require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && bytes(hostname).length != 0);
// make sure the name isn't already taken
require(apiIds[hostname] == 0);
numApis += 1;
apiIds[hostname] = numApis;
APIForSale storage api = apis[numApis];
api.pricePerCall = pricePerCall;
api.sellerUsername = sellerUsername;
api.apiName = apiName;
api.sellerAddress = msg.sender;
api.hostname = hostname;
api.docsUrl = docsUrl;
}
// ------------------------------------------------------------------------
// Get the ID number of an API given it's hostname
// ------------------------------------------------------------------------
function getApiId(string hostname) public view returns (uint) {
return apiIds[hostname];
}
// ------------------------------------------------------------------------
// Get info stored for the API but without the dynamic members, because solidity can't return dynamics to other smart contracts yet
// ------------------------------------------------------------------------
function getApiByIdWithoutDynamics(
uint apiId
)
public
view
returns (
uint pricePerCall,
bytes32 sellerUsername,
bytes32 apiName,
address sellerAddress
)
{
APIForSale storage api = apis[apiId];
pricePerCall = api.pricePerCall;
sellerUsername = api.sellerUsername;
apiName = api.apiName;
sellerAddress = api.sellerAddress;
}
// ------------------------------------------------------------------------
// Get info stored for an API by id
// ------------------------------------------------------------------------
function getApiById(
uint apiId
)
public
view
returns (
uint pricePerCall,
bytes32 sellerUsername,
bytes32 apiName,
address sellerAddress,
string hostname,
string docsUrl
)
{
APIForSale storage api = apis[apiId];
pricePerCall = api.pricePerCall;
sellerUsername = api.sellerUsername;
apiName = api.apiName;
sellerAddress = api.sellerAddress;
hostname = api.hostname;
docsUrl = api.docsUrl;
}
// ------------------------------------------------------------------------
// Get info stored for an API by hostname
// ------------------------------------------------------------------------
function getApiByName(
string _hostname
)
public
view
returns (
uint pricePerCall,
bytes32 sellerUsername,
bytes32 apiName,
address sellerAddress,
string hostname,
string docsUrl
)
{
uint apiId = apiIds[_hostname];
if (apiId == 0) {
return;
}
APIForSale storage api = apis[apiId];
pricePerCall = api.pricePerCall;
sellerUsername = api.sellerUsername;
apiName = api.apiName;
sellerAddress = api.sellerAddress;
hostname = api.hostname;
docsUrl = api.docsUrl;
}
// ------------------------------------------------------------------------
// Edit an API listing
// ------------------------------------------------------------------------
function editApi(uint apiId, uint pricePerCall, address sellerAddress, string docsUrl) public {
require(apiId != 0 && pricePerCall != 0 && sellerAddress != address(0));
APIForSale storage api = apis[apiId];
// prevent editing an empty api (effectively listing an api)
require(
api.pricePerCall != 0 && api.sellerUsername != "" && api.apiName != "" && bytes(api.hostname).length != 0 && api.sellerAddress != address(0)
);
// require that sender is the original api lister, or the contract owner
// the contract owner clause lets us recover a api listing if a dev loses access to their privkey
require(msg.sender == api.sellerAddress || msg.sender == owner);
api.pricePerCall = pricePerCall;
api.sellerAddress = sellerAddress;
api.docsUrl = docsUrl;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract DeconetToken is StandardToken, Ownable, Pausable {
// token naming etc
string public constant symbol = "DCO";
string public constant name = "Deconet Token";
uint8 public constant decimals = 18;
// contract version
uint public constant version = 4;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
// 1 billion tokens (1,000,000,000)
totalSupply_ = 1000000000 * 10**uint(decimals);
// transfer initial supply to msg.sender who is also contract owner
balances[msg.sender] = totalSupply_;
Transfer(address(0), msg.sender, totalSupply_);
// pause contract until we're ready to allow transfers
paused = true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens (just in case)
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Modifier to make a function callable only when called by the contract owner
// or if the contract is not paused.
// ------------------------------------------------------------------------
modifier whenOwnerOrNotPaused() {
require(msg.sender == owner || !paused);
_;
}
// ------------------------------------------------------------------------
// overloaded openzepplin method to add whenOwnerOrNotPaused modifier
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _value) public whenOwnerOrNotPaused returns (bool) {
return super.transfer(_to, _value);
}
// ------------------------------------------------------------------------
// overloaded openzepplin method to add whenOwnerOrNotPaused modifier
// ------------------------------------------------------------------------
function transferFrom(address _from, address _to, uint256 _value) public whenOwnerOrNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
// ------------------------------------------------------------------------
// overloaded openzepplin method to add whenOwnerOrNotPaused modifier
// ------------------------------------------------------------------------
function approve(address _spender, uint256 _value) public whenOwnerOrNotPaused returns (bool) {
return super.approve(_spender, _value);
}
// ------------------------------------------------------------------------
// overloaded openzepplin method to add whenOwnerOrNotPaused modifier
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public whenOwnerOrNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
// ------------------------------------------------------------------------
// overloaded openzepplin method to add whenOwnerOrNotPaused modifier
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public whenOwnerOrNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract APICalls is Ownable {
using SafeMath for uint;
// the amount rewarded to a seller for selling api calls per buyer
uint public tokenReward;
// the fee this contract takes from every sale. expressed as percent. so a value of 3 indicates a 3% txn fee
uint public saleFee;
// if the buyer has never paid, we need to pick a date for when they probably started using the API.
// This is in seconds and will be subtracted from "now"
uint public defaultBuyerLastPaidAt;
// address of the relay contract which holds the address of the registry contract.
address public relayContractAddress;
// the token address
address public tokenContractAddress;
// this contract version
uint public version;
// the amount that can be safely withdrawn from the contract
uint public safeWithdrawAmount;
// the address that is authorized to withdraw eth
address private withdrawAddress;
// the address that is authorized to report usage on behalf of deconet
address private usageReportingAddress;
// maps apiId to a APIBalance which stores how much each address owes
mapping(uint => APIBalance) internal owed;
// maps buyer addresses to whether or not accounts are overdrafted and more
mapping(address => BuyerInfo) internal buyers;
// Stores amounts owed and when buyers last paid on a per-api and per-user basis
struct APIBalance {
// maps address -> amount owed in wei
mapping(address => uint) amounts;
// basically a list of keys for the above map
address[] nonzeroAddresses;
// maps address -> tiemstamp of when buyer last paid
mapping(address => uint) buyerLastPaidAt;
}
// Stores basic info about a buyer including their lifetime stats and reputation info
struct BuyerInfo {
// whether or not the account is overdrafted or not
bool overdrafted;
// total number of overdrafts, ever
uint lifetimeOverdraftCount;
// credits on file with this contract (wei)
uint credits;
// total amount of credits used / spent, ever (wei)
uint lifetimeCreditsUsed;
// maps apiId to approved spending balance for each API per second.
mapping(uint => uint) approvedAmounts;
// maps apiId to whether or not the user has exceeded their approved amount
mapping(uint => bool) exceededApprovedAmount;
// total number of times exceededApprovedAmount has happened
uint lifetimeExceededApprovalAmountCount;
}
// Logged when API call usage is reported
event LogAPICallsMade(
uint apiId,
address indexed sellerAddress,
address indexed buyerAddress,
uint pricePerCall,
uint numCalls,
uint totalPrice,
address reportingAddress
);
// Logged when seller is paid for API calls
event LogAPICallsPaid(
uint apiId,
address indexed sellerAddress,
uint totalPrice,
uint rewardedTokens,
uint networkFee
);
// Logged when the credits from a specific buyer are spent on a specific api
event LogSpendCredits(
address indexed buyerAddress,
uint apiId,
uint amount,
bool causedAnOverdraft
);
// Logged when a buyer deposits credits
event LogDepositCredits(
address indexed buyerAddress,
uint amount
);
// Logged whena buyer withdraws credits
event LogWithdrawCredits(
address indexed buyerAddress,
uint amount
);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
version = 1;
// default token reward of 100 tokens.
// token has 18 decimal places so that's why 100 * 10^18
tokenReward = 100 * 10**18;
// default saleFee of 10%
saleFee = 10;
// 604,800 seconds = 1 week. this is the default for when a user started using an api (1 week ago)
defaultBuyerLastPaidAt = 604800;
// default withdrawAddress is owner
withdrawAddress = msg.sender;
usageReportingAddress = msg.sender;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens (just in case)
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Owner can transfer out any ETH
// ------------------------------------------------------------------------
function withdrawEther(uint amount) public {
require(msg.sender == withdrawAddress);
require(amount <= this.balance);
require(amount <= safeWithdrawAmount);
safeWithdrawAmount = safeWithdrawAmount.sub(amount);
withdrawAddress.transfer(amount);
}
// ------------------------------------------------------------------------
// Owner can set address of who can withdraw
// ------------------------------------------------------------------------
function setWithdrawAddress(address _withdrawAddress) public onlyOwner {
require(_withdrawAddress != address(0));
withdrawAddress = _withdrawAddress;
}
// ------------------------------------------------------------------------
// Owner can set address of who can report usage
// ------------------------------------------------------------------------
function setUsageReportingAddress(address _usageReportingAddress) public onlyOwner {
require(_usageReportingAddress != address(0));
usageReportingAddress = _usageReportingAddress;
}
// ------------------------------------------------------------------------
// Owner can set address of relay contract
// ------------------------------------------------------------------------
function setRelayContractAddress(address _relayContractAddress) public onlyOwner {
require(_relayContractAddress != address(0));
relayContractAddress = _relayContractAddress;
}
// ------------------------------------------------------------------------
// Owner can set address of token contract
// ------------------------------------------------------------------------
function setTokenContractAddress(address _tokenContractAddress) public onlyOwner {
require(_tokenContractAddress != address(0));
tokenContractAddress = _tokenContractAddress;
}
// ------------------------------------------------------------------------
// Owner can set token reward
// ------------------------------------------------------------------------
function setTokenReward(uint _tokenReward) public onlyOwner {
tokenReward = _tokenReward;
}
// ------------------------------------------------------------------------
// Owner can set the sale fee
// ------------------------------------------------------------------------
function setSaleFee(uint _saleFee) public onlyOwner {
saleFee = _saleFee;
}
// ------------------------------------------------------------------------
// Owner can set the default buyer last paid at
// ------------------------------------------------------------------------
function setDefaultBuyerLastPaidAt(uint _defaultBuyerLastPaidAt) public onlyOwner {
defaultBuyerLastPaidAt = _defaultBuyerLastPaidAt;
}
// ------------------------------------------------------------------------
// The API owner or the authorized deconet usage reporting address may report usage
// ------------------------------------------------------------------------
function reportUsage(uint apiId, uint numCalls, address buyerAddress) public {
// look up the registry address from relay contract
Relay relay = Relay(relayContractAddress);
address apiRegistryAddress = relay.apiRegistryContractAddress();
// get the module info from registry
APIRegistry apiRegistry = APIRegistry(apiRegistryAddress);
uint pricePerCall;
bytes32 sellerUsername;
bytes32 apiName;
address sellerAddress;
(pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId);
// make sure the caller is either the api owner or the deconet reporting address
require(sellerAddress != address(0));
require(msg.sender == sellerAddress || msg.sender == usageReportingAddress);
// make sure the api is actually valid
require(sellerUsername != "" && apiName != "");
uint totalPrice = pricePerCall.mul(numCalls);
require(totalPrice > 0);
APIBalance storage apiBalance = owed[apiId];
if (apiBalance.amounts[buyerAddress] == 0) {
// add buyerAddress to list of addresses with nonzero balance for this api
apiBalance.nonzeroAddresses.push(buyerAddress);
}
apiBalance.amounts[buyerAddress] = apiBalance.amounts[buyerAddress].add(totalPrice);
emit LogAPICallsMade(
apiId,
sellerAddress,
buyerAddress,
pricePerCall,
numCalls,
totalPrice,
msg.sender
);
}
// ------------------------------------------------------------------------
// Function to pay the seller for a single API buyer.
// Settles reported usage according to credits and approved amounts.
// ------------------------------------------------------------------------
function paySellerForBuyer(uint apiId, address buyerAddress) public {
// look up the registry address from relay contract
Relay relay = Relay(relayContractAddress);
address apiRegistryAddress = relay.apiRegistryContractAddress();
// get the module info from registry
APIRegistry apiRegistry = APIRegistry(apiRegistryAddress);
uint pricePerCall;
bytes32 sellerUsername;
bytes32 apiName;
address sellerAddress;
(pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId);
// make sure it's a legit real api
require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && sellerAddress != address(0));
uint buyerPaid = processSalesForSingleBuyer(apiId, buyerAddress);
if (buyerPaid == 0) {
return; // buyer paid nothing, we are done.
}
// calculate fee and payout
uint fee = buyerPaid.mul(saleFee).div(100);
uint payout = buyerPaid.sub(fee);
// log that we stored the fee so we know we can take it out later
safeWithdrawAmount += fee;
emit LogAPICallsPaid(
apiId,
sellerAddress,
buyerPaid,
tokenReward,
fee
);
// give seller some tokens for the sale
rewardTokens(sellerAddress, tokenReward);
// transfer seller the eth
sellerAddress.transfer(payout);
}
// ------------------------------------------------------------------------
// Function to pay the seller for all buyers with nonzero balance.
// Settles reported usage according to credits and approved amounts.
// ------------------------------------------------------------------------
function paySeller(uint apiId) public {
// look up the registry address from relay contract
Relay relay = Relay(relayContractAddress);
address apiRegistryAddress = relay.apiRegistryContractAddress();
// get the module info from registry
APIRegistry apiRegistry = APIRegistry(apiRegistryAddress);
uint pricePerCall;
bytes32 sellerUsername;
bytes32 apiName;
address sellerAddress;
(pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId);
// make sure it's a legit real api
require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && sellerAddress != address(0));
// calculate totalPayable for the api
uint totalPayable = 0;
uint totalBuyers = 0;
(totalPayable, totalBuyers) = processSalesForAllBuyers(apiId);
if (totalPayable == 0) {
return; // if there's nothing to pay, we are done here.
}
// calculate fee and payout
uint fee = totalPayable.mul(saleFee).div(100);
uint payout = totalPayable.sub(fee);
// log that we stored the fee so we know we can take it out later
safeWithdrawAmount += fee;
// we reward token reward on a "per buyer" basis. so multiply the reward to give by the number of actual buyers
uint totalTokenReward = tokenReward.mul(totalBuyers);
emit LogAPICallsPaid(
apiId,
sellerAddress,
totalPayable,
totalTokenReward,
fee
);
// give seller some tokens for the sale
rewardTokens(sellerAddress, totalTokenReward);
// transfer seller the eth
sellerAddress.transfer(payout);
}
// ------------------------------------------------------------------------
// Let anyone see when the buyer last paid for a given API
// ------------------------------------------------------------------------
function buyerLastPaidAt(uint apiId, address buyerAddress) public view returns (uint) {
APIBalance storage apiBalance = owed[apiId];
return apiBalance.buyerLastPaidAt[buyerAddress];
}
// ------------------------------------------------------------------------
// Get buyer info struct for a specific buyer address
// ------------------------------------------------------------------------
function buyerInfoOf(address addr)
public
view
returns (
bool overdrafted,
uint lifetimeOverdraftCount,
uint credits,
uint lifetimeCreditsUsed,
uint lifetimeExceededApprovalAmountCount
)
{
BuyerInfo storage buyer = buyers[addr];
overdrafted = buyer.overdrafted;
lifetimeOverdraftCount = buyer.lifetimeOverdraftCount;
credits = buyer.credits;
lifetimeCreditsUsed = buyer.lifetimeCreditsUsed;
lifetimeExceededApprovalAmountCount = buyer.lifetimeExceededApprovalAmountCount;
}
// ------------------------------------------------------------------------
// Gets the credits balance of a buyer
// ------------------------------------------------------------------------
function creditsBalanceOf(address addr) public view returns (uint) {
BuyerInfo storage buyer = buyers[addr];
return buyer.credits;
}
// ------------------------------------------------------------------------
// Lets a buyer add credits
// ------------------------------------------------------------------------
function addCredits(address to) public payable {
BuyerInfo storage buyer = buyers[to];
buyer.credits = buyer.credits.add(msg.value);
emit LogDepositCredits(to, msg.value);
}
// ------------------------------------------------------------------------
// Lets a buyer withdraw credits
// ------------------------------------------------------------------------
function withdrawCredits(uint amount) public {
BuyerInfo storage buyer = buyers[msg.sender];
require(buyer.credits >= amount);
buyer.credits = buyer.credits.sub(amount);
msg.sender.transfer(amount);
emit LogWithdrawCredits(msg.sender, amount);
}
// ------------------------------------------------------------------------
// Get the length of array of buyers who have a nonzero balance for a given API
// ------------------------------------------------------------------------
function nonzeroAddressesElementForApi(uint apiId, uint index) public view returns (address) {
APIBalance storage apiBalance = owed[apiId];
return apiBalance.nonzeroAddresses[index];
}
// ------------------------------------------------------------------------
// Get an element from the array of buyers who have a nonzero balance for a given API
// ------------------------------------------------------------------------
function nonzeroAddressesLengthForApi(uint apiId) public view returns (uint) {
APIBalance storage apiBalance = owed[apiId];
return apiBalance.nonzeroAddresses.length;
}
// ------------------------------------------------------------------------
// Get the amount owed for a specific api for a specific buyer
// ------------------------------------------------------------------------
function amountOwedForApiForBuyer(uint apiId, address buyerAddress) public view returns (uint) {
APIBalance storage apiBalance = owed[apiId];
return apiBalance.amounts[buyerAddress];
}
// ------------------------------------------------------------------------
// Get the total owed for an entire api for all nonzero buyers
// ------------------------------------------------------------------------
function totalOwedForApi(uint apiId) public view returns (uint) {
APIBalance storage apiBalance = owed[apiId];
uint totalOwed = 0;
for (uint i = 0; i < apiBalance.nonzeroAddresses.length; i++) {
address buyerAddress = apiBalance.nonzeroAddresses[i];
uint buyerOwes = apiBalance.amounts[buyerAddress];
totalOwed = totalOwed.add(buyerOwes);
}
return totalOwed;
}
// ------------------------------------------------------------------------
// Gets the amount of wei per second a buyer has approved for a specific api
// ------------------------------------------------------------------------
function approvedAmount(uint apiId, address buyerAddress) public view returns (uint) {
return buyers[buyerAddress].approvedAmounts[apiId];
}
// ------------------------------------------------------------------------
// Let the buyer set an approved amount of wei per second for a specific api
// ------------------------------------------------------------------------
function approveAmount(uint apiId, address buyerAddress, uint newAmount) public {
require(buyerAddress != address(0) && apiId != 0);
// only the buyer or the usage reporing system can change the buyers approval amount
require(msg.sender == buyerAddress || msg.sender == usageReportingAddress);
BuyerInfo storage buyer = buyers[buyerAddress];
buyer.approvedAmounts[apiId] = newAmount;
}
// ------------------------------------------------------------------------
// function to let the buyer set their approved amount of wei per second for an api
// this function also lets the buyer set the time they last paid for an API if they've never paid that API before.
// this is important because the total amount approved for a given transaction is based on a wei per second spending limit
// but the smart contract doesn't know when the buyer started using the API
// so with this function, a buyer can et the time they first used the API and the approved amount calculations will be accurate when the seller requests payment.
// ------------------------------------------------------------------------
function approveAmountAndSetFirstUseTime(
uint apiId,
address buyerAddress,
uint newAmount,
uint firstUseTime
)
public
{
require(buyerAddress != address(0) && apiId != 0);
// only the buyer or the usage reporing system can change the buyers approval amount
require(msg.sender == buyerAddress || msg.sender == usageReportingAddress);
APIBalance storage apiBalance = owed[apiId];
require(apiBalance.buyerLastPaidAt[buyerAddress] == 0);
apiBalance.buyerLastPaidAt[buyerAddress] = firstUseTime;
BuyerInfo storage buyer = buyers[buyerAddress];
buyer.approvedAmounts[apiId] = newAmount;
}
// ------------------------------------------------------------------------
// Gets whether or not a buyer exceeded their approved amount in the last seller payout
// ------------------------------------------------------------------------
function buyerExceededApprovedAmount(uint apiId, address buyerAddress) public view returns (bool) {
return buyers[buyerAddress].exceededApprovedAmount[apiId];
}
// ------------------------------------------------------------------------
// Reward user with tokens IF the contract has them in it's allowance
// ------------------------------------------------------------------------
function rewardTokens(address toReward, uint amount) private {
DeconetToken token = DeconetToken(tokenContractAddress);
address tokenOwner = token.owner();
// check balance of tokenOwner
uint tokenOwnerBalance = token.balanceOf(tokenOwner);
uint tokenOwnerAllowance = token.allowance(tokenOwner, address(this));
if (tokenOwnerBalance >= amount && tokenOwnerAllowance >= amount) {
token.transferFrom(tokenOwner, toReward, amount);
}
}
// ------------------------------------------------------------------------
// Process and settle balances for a single buyer for a specific api
// ------------------------------------------------------------------------
function processSalesForSingleBuyer(uint apiId, address buyerAddress) private returns (uint) {
APIBalance storage apiBalance = owed[apiId];
uint buyerOwes = apiBalance.amounts[buyerAddress];
uint buyerLastPaidAtTime = apiBalance.buyerLastPaidAt[buyerAddress];
if (buyerLastPaidAtTime == 0) {
// if buyer has never paid, assume they paid a week ago. or whatever now - defaultBuyerLastPaidAt is.
buyerLastPaidAtTime = now - defaultBuyerLastPaidAt; // default is 604,800 = 7 days of seconds
}
uint elapsedSecondsSinceLastPayout = now - buyerLastPaidAtTime;
uint buyerNowOwes = buyerOwes;
uint buyerPaid = 0;
bool overdrafted = false;
(buyerPaid, overdrafted) = chargeBuyer(apiId, buyerAddress, elapsedSecondsSinceLastPayout, buyerOwes);
buyerNowOwes = buyerOwes.sub(buyerPaid);
apiBalance.amounts[buyerAddress] = buyerNowOwes;
// if the buyer now owes zero, then remove them from nonzeroAddresses
if (buyerNowOwes != 0) {
removeAddressFromNonzeroBalancesArray(apiId, buyerAddress);
}
// if the buyer paid nothing, we are done here.
if (buyerPaid == 0) {
return 0;
}
// log the event
emit LogSpendCredits(buyerAddress, apiId, buyerPaid, overdrafted);
// log that they paid
apiBalance.buyerLastPaidAt[buyerAddress] = now;
return buyerPaid;
}
// ------------------------------------------------------------------------
// Process and settle balances for all buyers with a nonzero balance for a specific api
// ------------------------------------------------------------------------
function processSalesForAllBuyers(uint apiId) private returns (uint totalPayable, uint totalBuyers) {
APIBalance storage apiBalance = owed[apiId];
uint currentTime = now;
address[] memory oldNonzeroAddresses = apiBalance.nonzeroAddresses;
apiBalance.nonzeroAddresses = new address[](0);
for (uint i = 0; i < oldNonzeroAddresses.length; i++) {
address buyerAddress = oldNonzeroAddresses[i];
uint buyerOwes = apiBalance.amounts[buyerAddress];
uint buyerLastPaidAtTime = apiBalance.buyerLastPaidAt[buyerAddress];
if (buyerLastPaidAtTime == 0) {
// if buyer has never paid, assume they paid a week ago. or whatever now - defaultBuyerLastPaidAt is.
buyerLastPaidAtTime = now - defaultBuyerLastPaidAt; // default is 604,800 = 7 days of seconds
}
uint elapsedSecondsSinceLastPayout = currentTime - buyerLastPaidAtTime;
uint buyerNowOwes = buyerOwes;
uint buyerPaid = 0;
bool overdrafted = false;
(buyerPaid, overdrafted) = chargeBuyer(apiId, buyerAddress, elapsedSecondsSinceLastPayout, buyerOwes);
totalPayable = totalPayable.add(buyerPaid);
buyerNowOwes = buyerOwes.sub(buyerPaid);
apiBalance.amounts[buyerAddress] = buyerNowOwes;
// if the buyer still owes something, make sure we keep them in the nonzeroAddresses array
if (buyerNowOwes != 0) {
apiBalance.nonzeroAddresses.push(buyerAddress);
}
// if the buyer paid more than 0, log the spend.
if (buyerPaid != 0) {
// log the event
emit LogSpendCredits(buyerAddress, apiId, buyerPaid, overdrafted);
// log that they paid
apiBalance.buyerLastPaidAt[buyerAddress] = now;
// add to total buyer count
totalBuyers += 1;
}
}
}
// ------------------------------------------------------------------------
// given a specific buyer, api, and the amount they owe, we need to figure out how much to pay
// the final amount paid is based on the chart below:
// if credits >= approved >= owed then pay owed
// if credits >= owed > approved then pay approved and mark as exceeded approved amount
// if owed > credits >= approved then pay approved and mark as overdrafted
// if owed > approved > credits then pay credits and mark as overdrafted
// ------------------------------------------------------------------------
function chargeBuyer(
uint apiId,
address buyerAddress,
uint elapsedSecondsSinceLastPayout,
uint buyerOwes
)
private
returns (
uint paid,
bool overdrafted
)
{
BuyerInfo storage buyer = buyers[buyerAddress];
uint approvedAmountPerSecond = buyer.approvedAmounts[apiId];
uint approvedAmountSinceLastPayout = approvedAmountPerSecond.mul(elapsedSecondsSinceLastPayout);
// do we have the credits to pay owed?
if (buyer.credits >= buyerOwes) {
// yay, buyer can pay their debits
overdrafted = false;
buyer.overdrafted = false;
// has buyer approved enough to pay what they owe?
if (approvedAmountSinceLastPayout >= buyerOwes) {
// approved is greater than owed.
// mark as not exceeded approved amount
buyer.exceededApprovedAmount[apiId] = false;
// we can pay the entire debt
paid = buyerOwes;
} else {
// they have no approved enough
// mark as exceeded
buyer.exceededApprovedAmount[apiId] = true;
buyer.lifetimeExceededApprovalAmountCount += 1;
// we can only pay the approved portion of the debt
paid = approvedAmountSinceLastPayout;
}
} else {
// buyer spent more than they have. mark as overdrafted
overdrafted = true;
buyer.overdrafted = true;
buyer.lifetimeOverdraftCount += 1;
// does buyer have more credits than the amount they've approved?
if (buyer.credits >= approvedAmountSinceLastPayout) {
// they have enough credits to pay approvedAmountSinceLastPayout, so pay that
paid = approvedAmountSinceLastPayout;
} else {
// the don't have enough credits to pay approvedAmountSinceLastPayout
// so just pay whatever credits they have
paid = buyer.credits;
}
}
buyer.credits = buyer.credits.sub(paid);
buyer.lifetimeCreditsUsed = buyer.lifetimeCreditsUsed.add(paid);
}
function removeAddressFromNonzeroBalancesArray(uint apiId, address toRemove) private {
APIBalance storage apiBalance = owed[apiId];
bool foundElement = false;
for (uint i = 0; i < apiBalance.nonzeroAddresses.length-1; i++) {
if (apiBalance.nonzeroAddresses[i] == toRemove) {
foundElement = true;
}
if (foundElement == true) {
apiBalance.nonzeroAddresses[i] = apiBalance.nonzeroAddresses[i+1];
}
}
if (foundElement == true) {
apiBalance.nonzeroAddresses.length--;
}
}
}
|
------------------------------------------------------------------------ Function to pay the seller for a single API buyer. Settles reported usage according to credits and approved amounts. ------------------------------------------------------------------------ look up the registry address from relay contract get the module info from registry make sure it&39;s a legit real api
|
function paySellerForBuyer(uint apiId, address buyerAddress) public {
Relay relay = Relay(relayContractAddress);
address apiRegistryAddress = relay.apiRegistryContractAddress();
APIRegistry apiRegistry = APIRegistry(apiRegistryAddress);
uint pricePerCall;
bytes32 sellerUsername;
bytes32 apiName;
address sellerAddress;
(pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId);
require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && sellerAddress != address(0));
uint buyerPaid = processSalesForSingleBuyer(apiId, buyerAddress);
if (buyerPaid == 0) {
}
uint payout = buyerPaid.sub(fee);
emit LogAPICallsPaid(
apiId,
sellerAddress,
buyerPaid,
tokenReward,
fee
);
}
| 2,307,803
|
./full_match/5/0x213816e69A21320D086a40Af97A5151445e8bFDE/sources/contracts/DeedTenantProvisioning.sol
|
Mark Deed Tenant as deployed/
|
function startTenant(uint256 _nftId) external onlyProvisioningManager(_nftId) canStart(_nftId) {
tenantStatus[_nftId] = true;
emit TenantStarted(_msgSender(), _nftId);
}
| 7,060,014
|
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/stargate/l2/Stargate.sol
|
function to bridge tokens after swapping. this is different from bridgeAfterSwap since this function holds the logic for swapping tokens too. This method is payable because the caller is doing token transfer and briding operation for usage, refer to controller implementations encodedData for bridge should follow the sequence of properties in Stargate-BridgeData struct swapId routeId for the swapImpl swapData encoded data for swap stargateBridgeData encoded data for StargateBridgeData/
|
function swapAndBridge(
uint32 swapId,
bytes calldata swapData,
StargateBridgeDataNoToken calldata stargateBridgeData
) external payable {
(bool success, bytes memory result) = socketRoute
.getRoute(swapId)
.delegatecall(swapData);
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
(uint256 bridgeAmount, address token) = abi.decode(
result,
(uint256, address)
);
if (token == NATIVE_TOKEN_ADDRESS) {
routerETH.swapETH{
value: bridgeAmount + stargateBridgeData.optionalValue
}(
stargateBridgeData.stargateDstChainId,
payable(stargateBridgeData.senderAddress),
abi.encodePacked(stargateBridgeData.receiverAddress),
bridgeAmount,
stargateBridgeData.minReceivedAmt
);
ERC20(token).safeApprove(address(router), bridgeAmount);
{
stargateBridgeData.stargateDstChainId,
stargateBridgeData.srcPoolId,
stargateBridgeData.dstPoolId,
bridgeAmount,
stargateBridgeData.minReceivedAmt,
IBridgeStargate.lzTxObj(
stargateBridgeData.destinationGasLimit,
0,
"0x"
),
abi.encodePacked(stargateBridgeData.receiverAddress),
stargateBridgeData.destinationPayload
);
}
}
emit SocketBridge(
bridgeAmount,
token,
stargateBridgeData.stargateDstChainId,
StargateIdentifier,
msg.sender,
stargateBridgeData.receiverAddress,
stargateBridgeData.metadata
);
}
| 11,003,428
|
./full_match/4/0x95802e111aca8AfF6C060d2f091f8a4D5f4a8C12/sources/contracts/token.sol
|
SPDX-License-Identifier: Unlicensed
|
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);
██╗████████╗███████╗ ██╗ ██╗████████╗
}
| 12,269,095
|
./full_match/5/0xf738870a8063a060f59E3754C89039663bA1b027/sources/contracts/messagePassingBridge/MessagePassingBridge.sol
|
Function for setting the bridge limits limits The bridge limits to set/
|
function setBridgeLimits(BridgeLimits memory limits) external onlyOwnerOrGuardian {
bridgeLimits = limits;
}
| 1,858,638
|
./full_match/1/0x5B458d71a353384087CE1c48dA405D9cab14d155/sources/vesper-strategies/contracts/strategies/frax-lend/FraxLendVesperXy.sol
|
Repay all borrow amount and set min borrow limit to 0. This action usually done when loss is detected in strategy. 0 borrow limit make sure that any future rebalance do not borrow again./ Accrue and update interest
|
function repayAll() external onlyKeeper {
fraxLend.addInterest();
_repay(_borrowedFromFraxLend());
minBorrowLimit = 0;
maxBorrowLimit = 0;
}
| 9,703,267
|
pragma solidity 0.5.17;
import "./BaseJumpRateModelV2.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's JumpRateModel Contract V2 for V2 cTokens
* @author Arr00
* @notice Supports only for V2 cTokens
*/
contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 {
/**
* @notice Calculates the current borrow rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256) {
return getBorrowRateInternal(cash, borrows, reserves);
}
constructor(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_,
address owner_
) public BaseJumpRateModelV2(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, owner_) {}
}
pragma solidity 0.5.17;
import "./SafeMath.sol";
/**
* @title Logic for Compound's JumpRateModel Contract V2.
* @author Compound (modified by Dharma Labs, refactored by Arr00)
* @notice Version 2 modifies Version 1 by enabling updateable parameters.
*/
contract BaseJumpRateModelV2 {
using SafeMath for uint256;
event NewInterestParams(
uint256 baseRatePerBlock,
uint256 multiplierPerBlock,
uint256 jumpMultiplierPerBlock,
uint256 kink
);
/**
* @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly
*/
address public owner;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint256 public constant blocksPerYear = 2102400;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint256 public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint256 public baseRatePerBlock;
/**
* @notice The multiplierPerBlock after hitting a specified utilization point
*/
uint256 public jumpMultiplierPerBlock;
/**
* @notice The utilization point at which the jump multiplier is applied
*/
uint256 public kink;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
*/
constructor(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_,
address owner_
) internal {
owner = owner_;
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
/**
* @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModel(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_
) external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, 1e18]
*/
function utilizationRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) public pure returns (uint256) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
return borrows.mul(1e18).div(cash.add(borrows).sub(reserves));
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRateInternal(
uint256 cash,
uint256 borrows,
uint256 reserves
) internal view returns (uint256) {
uint256 util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
} else {
uint256 normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
uint256 excessUtil = util.sub(kink);
return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate);
}
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) public view returns (uint256) {
uint256 oneMinusReserveFactor = uint256(1e18).sub(reserveFactorMantissa);
uint256 borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint256 rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
/**
* @notice Internal function to update the parameters of the interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModelInternal(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_
) internal {
baseRatePerBlock = baseRatePerYear.div(blocksPerYear);
multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_));
jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear);
kink = kink_;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);
}
}
pragma solidity 0.5.17;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
pragma solidity 0.5.17;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(
uint256 a,
uint256 b,
string memory errorMessage
) 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
Internal function to update the parameters of the interest rate model baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point kink_ The utilization point at which the jump multiplier is applied/
|
function updateJumpRateModelInternal(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_
) internal {
baseRatePerBlock = baseRatePerYear.div(blocksPerYear);
multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_));
jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear);
kink = kink_;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);
}
| 555,213
|
//SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.4;
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./SVGBuffer.sol";
library Utils {
using SVGBuffer for bytes;
using SignedSafeMath for int256;
using Strings for uint256;
function stringToUint(string memory s)
internal
pure
returns (uint256 result)
{
bytes memory b = bytes(s);
uint256 i;
result = 0;
for (i = 0; i < b.length; i++) {
uint256 c = uint256(uint8(b[i]));
if (c >= 48 && c <= 57) {
result = result * 10 + (c - 48);
}
}
}
// special toString for signed 16 bit ints
function toString(int16 val) public view returns (string memory) {
bytes memory buffer = new bytes(8192);
if (val >= 0) buffer.append(uint256(val).toString());
else {
buffer.append("-");
buffer.append(uint256(int256(val).mul(-1)).toString());
}
return buffer.toString();
}
// TODO: fix overflow error
function toHexColor(
bytes memory buffer,
uint256 rgb
) internal pure {
require(SVGBuffer.hasCapacityFor(buffer, 6), "Buffer.rect: no capacity for color");
assembly {
function hexrgb(x, v) -> y {
let blo := and(v, 0xf)
let bhi := and(shr(4, v), 0xf)
let glo := and(shr(8, v), 0xf)
let ghi := and(shr(12, v), 0xf)
let rlo := and(shr(16, v), 0xf)
let rhi := and(shr(20, v), 0xf)
mstore8(x, add(add(rhi, mul(div(rhi, 10), 39)), 48))
mstore8(add(x, 1), add(add(rlo, mul(div(rlo, 10), 39)), 48))
mstore8(add(x, 2), add(add(ghi, mul(div(ghi, 10), 39)), 48))
mstore8(add(x, 3), add(add(glo, mul(div(glo, 10), 39)), 48))
mstore8(add(x, 4), add(add(bhi, mul(div(bhi, 10), 39)), 48))
mstore8(add(x, 5), add(add(blo, mul(div(blo, 10), 39)), 48))
y := add(x, 6)
}
let strIdx := add(mload(add(buffer, 32)), add(buffer, 64))
strIdx := hexrgb(strIdx, rgb)
mstore(add(buffer, 32), sub(sub(strIdx, buffer), 64))
}
}
}
|
special toString for signed 16 bit ints
|
function toString(int16 val) public view returns (string memory) {
bytes memory buffer = new bytes(8192);
if (val >= 0) buffer.append(uint256(val).toString());
else {
buffer.append("-");
buffer.append(uint256(int256(val).mul(-1)).toString());
}
return buffer.toString();
}
| 902,284
|
//SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract CreateFreezer {
address public creatorOwner; // public state variable automatically has getter function
DeepFreeze[] public deployedFreezer; // public array automatically has getter function
mapping(address => DeepFreeze[]) public userFreezer; // address maps to array of freezers
constructor(){
creatorOwner = msg.sender;
// owner of the creator contract is the original deployer (i.e., protocol admin, not freezer owner)
}
function createFreezer(string memory hint_, bytes32 answer_) public {
DeepFreeze new_freezer_address = new DeepFreeze(msg.sender, hint_, answer_);
// pass caller to DeepFreeze constructor as eoa; makes them owner of a their freezer
userFreezer[msg.sender].push(new_freezer_address); // track freezers at the owner level
// NOTE self-destructed freezers are not popped as they may not be the last freezer in array.
// simply ignore them in UI
deployedFreezer.push(new_freezer_address);
}
}
contract DeepFreeze {
// Variables
address payable public owner; // publicly visible owner of the freezer
string internal hint; // only this contract can see this.
bytes32 internal answer; // only this contract can see this.
// Not used in version 0
// uint public launchblock; // block the freezer was locked at.
//uint public blocklock; // optional, lock the withdraw function for a certain number of blocks.
constructor(address eoa, string memory hint_, bytes32 answer_){ // see createFreezer
owner = payable(eoa); // owner is freezer creator as payable
hint = hint_;
answer = answer_;
// Not used in version 0
// launchblock = block.number;
// blocklock = 0; // default to no lock
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the freezer owner can do that!");
_;
}
/*
Not used in Version 0
modifier checkLock() {
require(block.number > launchblock + blocklock, "This contract is still time-locked!");
_;
}
function LockWithdraw(uint numblocks) public onlyOwner checkLock {
blocklock = numblocks;
}
*/
function requestHint() public onlyOwner view returns(string memory) {
return(hint);
}
function requestKey() public onlyOwner view returns(bytes32) {
return(answer);
}
function deposit() public payable {
// accept deposits from anyone - ONLY THE BLOCKCHAIN's NATIVE ASSET! NOT ERC-20
}
function getBalance() public view returns(uint){
return address(this).balance;
}
function withdraw(string memory passphrase_) public onlyOwner checkLock {
require( keccak256(abi.encodePacked(passphrase_)) == answer, "Your passphrase is wrong.");
require (getBalance() != 0, "There's nothing to withdraw.");
// Input code for withdrawing a specific ERC-20 asset.
selfdestruct(owner); // automatically sends **ETH** to owner address upon contract death.
// ONLY ETH. Don't self destruct with ERC-20 balance!
}
}
|
Input code for withdrawing a specific ERC-20 asset. ONLY ETH. Don't self destruct with ERC-20 balance!
|
function withdraw(string memory passphrase_) public onlyOwner checkLock {
require( keccak256(abi.encodePacked(passphrase_)) == answer, "Your passphrase is wrong.");
require (getBalance() != 0, "There's nothing to withdraw.");
}
| 6,383,644
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
//struct used for all registered airlines
struct AirLine {
address airLineAddress;
bool isRegestered;
}
//struct used for alirlines who paied the fees
struct PaymentAirLine {
address airLineAddress;
bool isPayed;
}
//defining mapping for above
mapping(address => AirLine) private regesteredAirLines;
mapping(address => PaymentAirLine) private paidAirlines;
//needed for voting process
address[] multiCalls = new address[](0);
mapping(address => uint) private voteCount;
// Insurance Resource
uint public insuranceCount;
struct Insurance {
uint id;
uint flightId;
uint amountPaid;
address owner;
}
//capturing insurance information using diffrent ways
mapping(uint => Insurance) public insurancesById;
mapping(address => uint[]) private passengerToInsurances;
mapping(uint => uint[]) private flightToInsurances;
mapping(address => uint) public creditedAmounts;
mapping(bytes32 => uint) flightKeyToId;
mapping(address => uint256) private authorizedCaller;
// defininsg events
event InsurancePurchased(uint id);
event InsuranceCredited(uint id);
event AmountWithdrawn(address _address, uint amountWithdrawn);
event AuthorizedContract(address authContract);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
// a function to identify if a given airline is regestered
function isRegisteredAirline(address airLineAddress)external requireIsOperational returns(bool)
{
return (regesteredAirLines[airLineAddress].isRegestered== true);
}
function getMultiCall() external requireIsOperational returns(uint){
return multiCalls.length;
}
// required to count votes
function addVoterCounter(address airline) external requireIsOperational{
uint vote = voteCount[airline];
voteCount[airline] = vote.add(1);
}
//returning vote counts per airline
function getVoterCounter(address airline) external requireIsOperational returns(uint){
return voteCount[airline];
}
//retrive insurance records using diffrent ways
function getInsurancesByFlight(uint _flightId)
requireIsOperational
public
view
returns (uint [])
{
return flightToInsurances[_flightId];
}
function getInsurance(uint _id)
requireIsOperational
public
view
returns (uint id, uint flightId, uint amountPaid, address owner)
{
Insurance memory insurance = insurancesById[_id];
id = insurance.id;
flightId = insurance.flightId;
amountPaid = insurance.amountPaid;
owner = insurance.owner;
}
function authorizeCaller
(
address contractAddress
)
external
requireContractOwner
{
authorizedCaller[contractAddress] = 1;
emit AuthorizedContract(contractAddress);
}
// find if a given airline is a registered airline
function isAirline
(
address account
)
external
returns(bool)
{
return (regesteredAirLines[account].isRegestered== true);
}
// record the registeration for a given aireline
function registerPayment
(
address account
)
external
{
paidAirlines[account]=PaymentAirLine(account,true);
}
// find if a given airline has paied the fees
function isPaidAirline
(
address account
)
external
returns(bool)
{
return (paidAirlines[account].isPayed == true);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address LocalAirLineAddress
)
external
requireIsOperational
{
regesteredAirLines[LocalAirLineAddress]=AirLine(LocalAirLineAddress,true);
multiCalls.push(LocalAirLineAddress);
}
// passingers
/**
* @dev Buy insurance for a flight
*
*/
function buy
(uint _flightId, address _owner,uint _amountPaid)
requireIsOperational
external
{
insuranceCount = insuranceCount.add(1);
insurancesById[insuranceCount] = Insurance({id: insuranceCount,flightId: _flightId, amountPaid: _amountPaid,owner: _owner});
flightToInsurances[_flightId].push(insuranceCount);
passengerToInsurances[_owner].push(insuranceCount);
emit InsurancePurchased(insurancesById[insuranceCount].id);
}
function getFlightIdByKey(bytes32 _key)
requireIsOperational
external
view
returns (uint)
{
return flightKeyToId[_key];
}
/**
* @dev Credits payouts to insurees, multiply by 1.5
*/
function creditInsurance
(uint _id, uint _amountToCredit)
requireIsOperational
public
{
Insurance memory insurance = insurancesById[_id];
creditedAmounts[insurance.owner] = creditedAmounts[insurance.owner].add(_amountToCredit.mul(3).div(2));
emit InsuranceCredited(_id);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(uint _amountToWithdraw, address _address)
requireIsOperational
public
payable
{
creditedAmounts[_address] = creditedAmounts[_address].sub(_amountToWithdraw);
_address.transfer(_amountToWithdraw);
emit AmountWithdrawn(_address, _amountToWithdraw);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
external
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Buy insurance for a flight/
|
function buy
(uint _flightId, address _owner,uint _amountPaid)
requireIsOperational
external
{
insuranceCount = insuranceCount.add(1);
flightToInsurances[_flightId].push(insuranceCount);
passengerToInsurances[_owner].push(insuranceCount);
emit InsurancePurchased(insurancesById[insuranceCount].id);
}
| 997,975
|
./full_match/80001/0xC983670234A6E4a2AB4A432cDBABC3F05274460e/sources/PolyApart/chef/PolyApartMasterChef.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accApartPerShare).div(1e18).sub(
user.rewardDebt
);
if (pending > 0) {
safeApartTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
pool.lpSupply = pool.lpSupply.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accApartPerShare).div(1e18);
emit Withdraw(msg.sender, _pid, _amount);
}
| 9,512,006
|
./full_match/11155111/0x23f054d07Fb93ea7F695C186e3351cB3AD8834cf/sources/contracts/Wager.sol
|
Function to place a wager for a specific seat Store the wager and player's address
|
function placeWager(uint256 seatId) external payable {
require(!gameStarted, "Game has already started");
require(seatId < TOTAL_SEATS, "Invalid seat ID");
int price = getLatestPrice();
require(msg.value == uint256(price) * 5 / 10**8, "Incorrect wager amount, must be 5 USD worth of Ether");
require(players[seatId] == address(0), "Seat already taken");
wagers[seatId] = msg.value;
players[seatId] = msg.sender;
emit WagerPlaced(seatId, msg.sender, msg.value);
}
| 3,821,738
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.10 <0.9.0;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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: contracts/MerkleProof.sol
pragma solidity ^0.8.9;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
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.
*/
using Strings for uint256;
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal 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(i.toString(), computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(i.toString(), proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// 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)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.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());
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @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: contracts/PublicPrivateVoucherMinter.sol
abstract contract PublicPrivateVoucherMinter is Ownable {
// event to log mint detail
event MinterCreated(address _address);
event PublicMint (address _address, uint256 _amount, uint256 _value);
event PrivateMint(address _address, uint256 id, uint256 _amount, uint256 _value);
event VoucherMint(address _address, uint256 id, uint256 _amount, uint256 _value);
event ProjectMint(address _address, uint256 _amount, string _reason);
struct MinterConfig {
bool isPublicMintActive; // can call publicMint only when isPublicMintActive is true
bool isPrivateMintActive; // can call privateMint only when isPrivateMintActive is true
bool isVoucherMintActive; // can call voucherMint only when isVoucherMintActive is true
uint256 publicMintPrice; // price for publicMint
uint256 privateMintPrice; // price for privateMint
uint256 maxPublicMintAmount; // maximum amount per publicMint transaction
uint256 maxPrivateMintAmount; // maximum amount per privateMint transaction
uint256 maxTotalSupply; // maximum supply
uint256 maxPrivateMintSupply; // maximum supply for private round
}
// Sale counter
uint256 public totalPublicSold;
uint256 public totalPrivateSold;
uint256 public totalVoucherClaimed;
uint256 public totalVoucherIssued;
uint256 public totalProjectMint;
address public beneficiary;
bytes32 private _merkleRoot;
uint256 private _proofLength;
// a mapping from voucher/whitelised Id to the amount used
mapping(uint256 => uint256) private _amountUsed;
// Operator
address private _operator; // address of operator who can set parameter of this contract
MinterConfig public minterConfig;
constructor (MinterConfig memory config, address payable _beneficiary) {
setMinterConfig(config);
setBeneficiary(_beneficiary);
setOperator(_msgSender());
}
function setMinterConfig(MinterConfig memory config) public onlyOwner {
minterConfig = config;
}
/// @notice Recipient of revenues
function setBeneficiary(address payable _beneficiary) public onlyOwner {
require(_beneficiary != address(0), "Not the zero address");
beneficiary = _beneficiary;
}
/**
@dev Called by after all limited have been put in place; must perform all contract-specific sale logic, e.g.
ERC721 minting.
@param to The recipient of the item(s).
@param amount The number of items allowed to be purchased
**/
function _mintTo(address to, uint256 amount) internal virtual;
function togglePublicMintActive() external onlyOwnerAndOperator {
require (minterConfig.publicMintPrice > 0, "Public Mint Price is zero");
minterConfig.isPublicMintActive = !minterConfig.isPublicMintActive;
}
function togglePrivateMintActive() external onlyOwnerAndOperator {
require (minterConfig.privateMintPrice > 0, "Private Mint Price is zero");
minterConfig.isPrivateMintActive = !minterConfig.isPrivateMintActive;
}
function toggleVoucherMintActive() external onlyOwnerAndOperator {
minterConfig.isVoucherMintActive = !minterConfig.isVoucherMintActive;
}
function totalSold() external view returns (uint256) {
return totalPublicSold + totalPrivateSold + totalVoucherClaimed;
}
// set maxTotalSupply
function setMaxTotalSupply(uint256 supply) external onlyOwnerAndOperator {
minterConfig.maxTotalSupply = supply;
}
// set parameter for public mint
function setPublicMintDetail(uint256 price, uint256 amount) external onlyOwnerAndOperator {
require(!minterConfig.isPublicMintActive, "Public mint is active");
minterConfig.publicMintPrice = price;
minterConfig.maxPublicMintAmount = amount;
}
// set parameter for private mint
function setPrivateMintDetail(uint256 price, uint256 amount, uint256 supply) external onlyOwnerAndOperator {
require(!minterConfig.isPrivateMintActive, "Private mint is active");
minterConfig.privateMintPrice = price;
minterConfig.maxPrivateMintAmount = amount;
minterConfig.maxPrivateMintSupply = supply;
}
// set parameter for voucher/private mint
function setVoucherDetail(bytes32 merkleRoot, uint256 proofLength, uint256 voucherAmount) external onlyOwnerAndOperator {
_merkleRoot = merkleRoot;
_proofLength = proofLength;
totalVoucherIssued = voucherAmount;
}
function publicMint(uint256 amount) public payable {
require(minterConfig.isPublicMintActive,"Public mint is closed");
require(amount > 0,"Amount is zero");
require(amount <= minterConfig.maxPublicMintAmount,"Amount is greater than maximum");
require(totalProjectMint + totalPublicSold + totalPrivateSold + totalVoucherIssued + amount <= minterConfig.maxTotalSupply,"Exceed maxTotalSupply");
require(minterConfig.publicMintPrice * amount <= msg.value, "Insufficient fund");
address to = _msgSender();
_mintTo(to, amount);
totalPublicSold += amount;
emit PublicMint(to, amount, msg.value);
}
function privateMint( uint256 amount,
uint256 whitelistedId, uint256 whitelistedAmount, bytes32[] calldata proof ) public payable {
require(minterConfig.isPrivateMintActive,"Private mint is closed");
address to = _msgSender();
bytes32 hash = keccak256(abi.encodePacked(whitelistedId, address(this), 'W', to, whitelistedAmount));
require(proof.length == _proofLength,"Invalid whitelisted detail");
require(MerkleProof.verify(proof, _merkleRoot, hash),"Invalid whitelisted detail");
require(_amountUsed[whitelistedId] == 0, "Whielisted has been used");
if (whitelistedAmount == 0) {
require(amount <= minterConfig.maxPrivateMintAmount,"Amount is greater than maximum");
} else {
require(amount <= whitelistedAmount,"Amount is greater than maximum");
}
require(amount > 0,"Amount is zero");
require(totalPrivateSold + amount <= minterConfig.maxPrivateMintSupply,"Exceed maxPrivateMintSupply");
require(minterConfig.privateMintPrice * amount <= msg.value, "Insufficient fund");
_mintTo(to, amount);
_amountUsed[whitelistedId] = amount;
totalPrivateSold += amount;
emit PrivateMint(to, whitelistedId, amount, msg.value);
}
function voucherMint( uint256 amount,
uint256 voucherId, uint256 voucherAmount, uint256 voucherPrice, bytes32[] calldata proof) public payable {
require(minterConfig.isVoucherMintActive,"Voucher mint is closed");
address to = _msgSender();
bytes32 hash = keccak256(abi.encodePacked(voucherId, address(this), 'V', to, voucherAmount, voucherPrice));
require(proof.length == _proofLength,"Invalid whitelisted detail");
require(MerkleProof.verify(proof, _merkleRoot, hash),"Invalid voucher detail");
require(_amountUsed[voucherId] + amount <= voucherAmount,"Ammount is greater than voucher");
require(amount > 0,"Amount is zero");
require(voucherPrice * amount <= msg.value, "Insufficient fund");
_mintTo(to, amount);
_amountUsed[voucherId] += amount;
totalVoucherClaimed += amount;
emit VoucherMint(to, voucherId, amount, msg.value);
}
function _projectMint(address to, uint256 amount, string memory reason) internal {
_mintTo(to, amount);
totalProjectMint += amount;
emit ProjectMint(to, amount, reason);
}
function getAmountUsed(uint256 voucherId) external view returns (uint256) {
return _amountUsed[voucherId];
}
//////////////////////////////////////////////////////////////////////////////////////
// Function to withdraw fund from contract
/////
function withdraw() external onlyOwner {
uint256 _balance = address(this).balance;
Address.sendValue(payable(beneficiary), _balance);
}
function withdraw(uint256 balance) external onlyOwner {
Address.sendValue(payable(beneficiary), balance);
}
function transferERC20(IERC20 token) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(beneficiary, balance);
}
function transferERC20(IERC20 token, uint256 amount) external onlyOwner {
token.transfer(beneficiary, amount);
}
function donate() external payable {
// thank you
}
// set Operator
function setOperator(address operator) public onlyOwner {
require(operator != address(0), "Not the zero address");
_operator = operator;
}
function minterStatus() public view returns (
bool isPublicMintActive_,
bool isPrivateMintActive_,
bool isVoucherMintActive_,
uint256 publicMintPrice_,
uint256 privateMintPrice_,
uint256 maxPublicMintAmount_,
uint256 maxPrivateMintAmount_,
uint256 maxTotalSupply_,
uint256 maxPrivateMintSupply_,
uint256 totalPublicSold_,
uint256 totalPrivateSold_,
uint256 totalVoucherClaimed_,
uint256 totalVoucherIssued_,
uint256 totalProjectMint_
)
{
isPublicMintActive_ = minterConfig.isPublicMintActive;
isPrivateMintActive_ = minterConfig.isPrivateMintActive;
isVoucherMintActive_ = minterConfig.isVoucherMintActive;
publicMintPrice_ = minterConfig.publicMintPrice;
privateMintPrice_ = minterConfig.privateMintPrice;
maxPublicMintAmount_ = minterConfig.maxPublicMintAmount;
maxPrivateMintAmount_ = minterConfig.maxPrivateMintAmount;
maxTotalSupply_ = minterConfig.maxTotalSupply;
maxPrivateMintSupply_ = minterConfig.maxPrivateMintSupply;
totalPublicSold_ = totalPublicSold;
totalPrivateSold_ = totalPrivateSold;
totalVoucherClaimed_ = totalVoucherClaimed;
totalVoucherIssued_ = totalVoucherIssued;
totalProjectMint_ = totalProjectMint;
}
/**
* @dev Throws if called by any account other than the operator.
*/
modifier onlyOwnerAndOperator() {
require( _msgSender() == owner() || _msgSender() == _operator, "Caller is not the operator");
_;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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);
}
// File: @openzeppelin/contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
// File: contracts/ERC721S.sol
/**
* A modification of openzeppelin ERC721 for a small, sequential mint, non-burnable collection
* that implement IERC721, IERC721Metadata, and IERCEnumberable.
* The assumption for this contract are:
* - Token will be mint in sequential order
* - The total number of token can be pack in 2**32-1
*/
contract ERC721S is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenDetail {
// The address of the owner.
address owner;
// Mapping from TokenID to index in _allToken list
uint32 allTokensIndex;
// Mapping from TokenID to index in _ownedTokens list
uint32 ownedTokensIndex;
// Reserved for other used;
uint32 reserved;
}
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to token Detail
mapping(uint256 => TokenDetail) private _tokenDetail;
// 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;
// Mapping from owner to list of owned token IDs
mapping(address => uint32[]) private _ownedTokens;
// Array with all token ids, used for enumeration
uint32[] private _allTokens;
// Id of the fist token minted
uint32 private _currentIndex;
/**
* @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_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint32) {
return 1;
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* Returns the total amount of tokens burned in the contract.
*/
function _totalBurned() internal view returns (uint256) {
unchecked {
return _totalMinted() - _allTokens.length;
}
}
/**
* @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 virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokens[owner].length;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _tokenDetail[tokenId].owner;
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 overridden 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 = ERC721S.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 _tokenDetail[tokenId].owner != 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 = ERC721S.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints new token and transfers it to `to`.
*
* Requirements:
*
* - 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) internal virtual {
_safeMint(to, "");
}
/**
* @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, bytes memory _data) internal virtual {
uint256 tokenId = uint256(_currentIndex);
_mint(to);
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) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
uint32 tokenId = _currentIndex;
_beforeTokenTransfer(address(0), to, tokenId);
uint32[] storage toTokenList = _ownedTokens[to];
TokenDetail storage tokenDetail = _tokenDetail[tokenId];
tokenDetail.owner = to;
tokenDetail.ownedTokensIndex = uint32(toTokenList.length);
tokenDetail.allTokensIndex = uint32(_allTokens.length);
toTokenList.push(tokenId);
_allTokens.push(tokenId);
_currentIndex += 1;
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 = ERC721S.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
TokenDetail storage tokenDetail = _tokenDetail[tokenId];
uint32[] storage fromTokenList = _ownedTokens[owner];
// _removeTokenFromOwnerEnumeration(owner, tokenId);
uint32 tokenIndex = tokenDetail.ownedTokensIndex;
uint32 lastToken = fromTokenList[fromTokenList.length - 1];
if (lastToken != uint32(tokenId)) {
fromTokenList[tokenIndex] = lastToken;
_tokenDetail[lastToken].ownedTokensIndex = tokenIndex;
}
fromTokenList.pop();
// _removeTokenFromALLTokensEnumeration
uint32 lastAllToken = _allTokens[_allTokens.length - 1];
uint32 allTokenIndex = tokenDetail.allTokensIndex;
_allTokens[allTokenIndex] = lastAllToken;
tokenDetail.owner = address(0);
tokenDetail.allTokensIndex = 0;
tokenDetail.ownedTokensIndex = 0;
_allTokens.pop();
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(ERC721S.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);
_tokenDetail[tokenId].owner = to;
// _removeTokenFromOwnerEnumeration(from, tokenId);
uint32[] storage fromTokenList = _ownedTokens[from];
TokenDetail storage tokenDetail = _tokenDetail[tokenId];
uint32 tokenIndex = tokenDetail.ownedTokensIndex;
uint32 lastToken = fromTokenList[fromTokenList.length - 1];
fromTokenList[tokenIndex] = lastToken;
_tokenDetail[lastToken].ownedTokensIndex = tokenIndex;
fromTokenList.pop();
// _addTokenToOwnerEnumeration(to, tokenId);
uint32[] storage toTokenList = _ownedTokens[to];
tokenDetail.ownedTokensIndex = uint32(toTokenList.length);
toTokenList.push(uint32(tokenId));
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(ERC721S.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 See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
require(index < ERC721S.balanceOf(owner), "Owner index out of bounds");
return uint256(_ownedTokens[owner][index]);
}
function ownedBy(address owner) external view returns (uint256[] memory) {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint32[] storage ownedTokens = _ownedTokens[owner];
for (uint256 i; i < balance; i++) {
tokens[i] = uint256(ownedTokens[i]);
}
return tokens;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
require(index < ERC721S.totalSupply(), "Global index out of bounds");
return uint256(_allTokens[index]);
}
/**
* @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 {}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {}
}
// File: @openzeppelin/contracts/token/common/ERC2981.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol)
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// File: contracts/JCCGenesis.sol
interface ITokenURI {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IIsTokenLocked {
function isTokenLocked(uint256 tokenId) external view returns (bool);
}
contract JCCGenesis is
ERC721S,
PublicPrivateVoucherMinter,
ERC2981,
Pausable
{
using Strings for uint256;
// Constants
bytes4 constant tokenURIInterface = bytes4(keccak256("tokenURI(uint256)"));
bytes4 constant isTokenLockedInterface = bytes4(keccak256("isTokenLocked(uint256)"));
// Variable
uint256 public maxSupply = 555;
string public baseURI;
string public notRevealedURI = "https://assets.jokercharlie.com/jccgenesis/default.json";
string public baseExtension = ".json";
bool public revealed;
address public metadataContract;
address public lockerContract;
constructor (address payable beneficiary, address payable royaltyReceiver)
ERC721S("Joker Charlie Club Genesis", "JCCGENESIS")
PublicPrivateVoucherMinter(
PublicPrivateVoucherMinter.MinterConfig({
isPublicMintActive : false, // can call publicMint only when isPublicMintActive is true
isPrivateMintActive: false, // can call privateMint only when isPrivateMintActive is true
isVoucherMintActive: false, // can call voucherMint only when isVoucherMintActive is true
publicMintPrice: 0.555 ether, // price for publicMint
privateMintPrice: 0.555 ether, // price for privateMint
maxPublicMintAmount: 2, // maximum amount per publicMint transaction
maxPrivateMintAmount: 1, // default maximum amount per privateMint transaction
maxTotalSupply: 555, // maximum supply
maxPrivateMintSupply: 300 // maximum supply for previate mint
}),
beneficiary
)
{
require(beneficiary != address(0), "Not the zero address");
require(royaltyReceiver != address(0), "Not the zero address");
// setting initial royalty fee
_setDefaultRoyalty(royaltyReceiver, 1000);
}
/* This function will be used to mint the NFT to team-member, advisory, treasury and giveaway purpose.
These NFTs will be firstly mint to a segregated wallet for each corresponding purpose.
After that it will be transfer to the final destination from each segregated wallet.
*/
function projectMint() external onlyOwner {
require(totalProjectMint == 0, "Already mint");
_projectMint(0xeeb50494D097d68D95C333aA1D038189D2BaE6bB, 33, "for team member"); // TokenId 1 to 33
_projectMint(0x19d03a5E56240507934af26b194d38F76144815D, 30, "for advisor"); // TokenId 34 to 63
_projectMint(0x52FF836e109fB4Df3931Ee367a25f04EdDE92A89, 17, "for giveaway"); // TokenId 64 to 80
_projectMint(0x6dd041217aE648AE13b5DF1F60b1DE886FdFBEbf, 100, "for treasury"); // ToeknId 81 to 180
}
function setRoyaltyInfo(address receiver, uint96 feeBasisPoints)
external
onlyOwner
{
require(receiver != address(0), "Not the zero address");
_setDefaultRoyalty(receiver, feeBasisPoints);
}
function reveal()
external
onlyOwner
{
revealed = true;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function _mintTo(address to, uint256 amount) internal override
{
// require(!paused(), "Mint is paused"); // Already checks in _beforeTokenTransfer
require(totalSupply() + amount <= maxSupply, "Max supply limit exceed");
for (uint256 i; i < amount; i++) {
_safeMint(to);
}
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721S, ERC2981)
returns (bool)
{
return ERC721S.supportsInterface(interfaceId) ||
ERC2981.supportsInterface(interfaceId);
}
// TokenURI related functions
function setBaseTokenURI(string calldata uri)
external
onlyOwner
{
baseURI = uri;
}
function setNotRevealedURI(string calldata uri)
external
onlyOwner
{
notRevealedURI = uri;
}
function setMetadataContract(address metadata)
external
onlyOwner
{
if (metadata != address(0)) {
require(ERC165(metadata).supportsInterface(tokenURIInterface), "tokenURI(uint256) not supported");
}
metadataContract = metadata;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function baseTokenURI(uint256 tokenId) public view returns (string memory) {
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token");
if (revealed == false) {
return notRevealedURI;
} else if (metadataContract != address(0)) {
return ITokenURI(metadataContract).tokenURI(tokenId);
} else {
return baseTokenURI(tokenId);
}
}
// Locker relatd functions
function setLockerContract(address locker)
external
onlyOwner
{
if (locker != address(0)) {
require(ERC165(locker).supportsInterface(isTokenLockedInterface), "isTokenLocked(uint256) not supported");
}
lockerContract = locker;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
require(!paused(), "Contract is paused");
if (lockerContract != address(0)) {
require(!IIsTokenLocked(lockerContract).isTokenLocked(tokenId),"Token is locked");
}
super._beforeTokenTransfer(from, to, tokenId);
}
/// @notice Transfers the ownership of multiple NFTs from one address to another address
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenIds The NFTs to transfer
/// @param _data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory _data) external {
for (uint i; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], _data);
}
}
/// @notice Transfers the ownership of multiple NFTs from one address to another address
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenIds The NFTs to transfer
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) external {
for (uint i; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i]);
}
}
}
|
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);
}
| 46,374
|
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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/utils/Address.sol
//
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/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/utils/Strings.sol
//
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/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}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
//
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/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 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;
}
}
// 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/token/ERC721/extensions/ERC721Enumerable.sol
//
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
//
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
//
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// File: @chainlink/contracts/src/v0.8/VRFRequestIDBase.sol
//
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// File: @chainlink/contracts/src/v0.8/VRFConsumerBase.sol
//
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// File: src/contracts/Tierra.sol
//
pragma solidity ^0.8.6;
// Imports
// Tierra
abstract contract Tierra is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard, VRFConsumerBase {
// The total supply.
uint256 public maxSupply;
// The min/max number of NFTs that a user can purchase in one order.
uint256 public minQuantity = 1;
uint256 public maxQuantity = 100;
// Metadata URI.
string public baseURI = "";
string public fileEXT = ".json";
// The price of a single NFT token.
uint256 public price = 0.055 ether;
// The sale status.
bool public isSaleActive = false;
// The competition status.
bool public isCompetitionActive = true;
// The competition amount - 100 ETH!.
uint256 public constant competitionAmount = 100 ether;
// The competition's random number generator properties.
bytes32 internal keyHash;
uint256 public oracleFee;
bytes32 internal requestId;
uint256 public randomResult;
// Contract data.
struct ContractData {
uint256 maxSupply;
uint256 totalSupply;
uint256 remainingTokens;
address contractAddress;
bool isSaleActive;
bool isCompetitionActive;
uint256 competitionAmount;
uint256 price;
string baseURI;
uint256 oracleFee;
uint256 randomResult;
}
/**
* @dev Constructor.
* @param name: The contract name.
* @param symbol: The contract symbol.
* @param _maxSupply: The maximum token supply.
* @param _baseTokenURI: The base URI for token metadata.
* @param _isCompetitionEnabled: Enable the competition for this contract.
* @param vrfCoordinator: The Chainlink VRF coordinator address for the current network.
* @param linkContractAddress: The Chainlink token's contract address for the current network.
* @param _keyHash: The Chainlink oracle's keyhash for the current network.
* @param _oracleFee: The Chainlink oracle's transaction fee.
*/
constructor(
string memory name,
string memory symbol,
uint256 _maxSupply,
string memory _baseTokenURI,
bool _isCompetitionEnabled,
address vrfCoordinator,
address linkContractAddress,
bytes32 _keyHash,
uint256 _oracleFee
) ERC721(name, symbol) VRFConsumerBase(vrfCoordinator, linkContractAddress) {
maxSupply = _maxSupply;
baseURI = _baseTokenURI;
isCompetitionActive = _isCompetitionEnabled;
keyHash = _keyHash;
oracleFee = _oracleFee;
}
/**
* @dev Mint tokens.
* @param quantity: The number of tokens to mint.
*/
function mint(uint256 quantity) public payable {
require(!isSoldOut(), "Sold out.");
require(isSaleActive, "The sale is not active.");
require(quantity >= minQuantity, "Quantity must be at least 1.");
require(quantity <= maxQuantity, "Maximum quantity exceeded.");
require((totalSupply() + quantity) <= maxSupply, "Purchase exceeds remaining tokens.");
require(msg.value >= (price * quantity), "Incorrect amount sent.");
// Mint tokens.
for(uint256 i = 0; i < quantity; ++i) {
uint256 tokenIndex = totalSupply();
if (tokenIndex < maxSupply) {
_safeMint(msg.sender, tokenIndex);
}
}
// Trigger the competition payout when the last token is sold.
if (isSoldOut() && isCompetitionActive && ownerOf(maxSupply-1) == msg.sender) {
requestRandomness();
}
}
/**
* @dev Return all public contract data.
*/
function getData() public view virtual returns (ContractData memory) {
return ContractData(
maxSupply,
totalSupply(),
remainingTokens(),
address(this),
isSaleActive,
isCompetitionActive,
competitionAmount,
price,
baseURI,
oracleFee,
randomResult
);
}
/**
* @dev Return true if all tokens have been sold.
*/
function isSoldOut() public view virtual returns (bool) {
return totalSupply() >= maxSupply;
}
/**
* @dev Return the number of remaining tokens.
*/
function remainingTokens() public view virtual returns (uint256) {
return maxSupply - totalSupply();
}
/**
* @dev Set the flag isSaleActive.
* @param active: The sale's new active status.
*/
function setSaleActive(bool active) public onlyOwner {
isSaleActive = active;
}
/**
* @dev Call base class: ERC721Enumerable._beforeTokenTransfer().
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Call base class: ERC721Enumerable.supportsInterface().
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @dev Return the metadata URI for a token.
* @param tokenId: The id of the token to get the URI for.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
string memory uri = _baseURI();
return bytes(uri).length > 0
? string(abi.encodePacked(uri, Strings.toString(tokenId), fileEXT))
: "";
}
/**
* @dev Return the base URI for token metadata.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @dev Set the base URI for token metadata.
* @param uri: The new base URI.
*/
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
/**
* @dev Set the metadata URI file extension.
* @param ext: The new file extension.
*/
function setBaseEXT(string memory ext) public onlyOwner {
fileEXT = ext;
}
/**
* @dev Set the NFT token sale price.
* @param value: The new token price.
*/
function setPrice(uint256 value) public onlyOwner {
require(value > 0, "Price must be greater than 0.");
price = value;
}
/**
* @dev Set the max number of tokens that can be purchased in one order.
* @param value: The new max quantity.
*/
function setMaxQuantity(uint256 value) public onlyOwner {
require(value > 0, "Max quantity must be greater than 0.");
maxQuantity = value;
}
/**
* @dev Set the oracle fee for the chainlink network.
* @param value: The new oracle fee.
*/
function setOracleFee(uint256 value) public onlyOwner {
require(value > 0, "Oracle fee must be greater than 0.");
oracleFee = value;
}
/**
* @dev Return the contract's current ETH balance.
*/
function balance() public view virtual returns (uint256) {
return address(this).balance;
}
/**
* @dev Return the contract's current LINK balance.
*/
function linkBalance() public view virtual returns (uint256) {
return LINK.balanceOf(address(this));
}
/**
* @dev Withdraw the current ETH balance (minus the competition payout) to the owner's wallet.
*/
function withdraw() public payable onlyOwner {
uint256 amount = balance() - (isCompetitionActive ? competitionAmount : 0);
require(amount > 0, "Insufficient balance.");
payable(msg.sender).transfer(amount);
}
/**
* @dev Withdraw the current LINK balance to the owner's wallet.
*/
function linkWithdraw() public payable onlyOwner {
uint256 amount = linkBalance();
require(amount > 0, "Insufficient LINK balance.");
LINK.transfer(msg.sender, amount);
}
/**
* @dev Random number generator (requestRandomness()) callback function.
* @dev Send 100 ETH to a random address.
*/
function fulfillRandomness(bytes32 _requestId, uint256 randomness) internal override nonReentrant {
require(requestId == _requestId);
require(isSoldOut(), "The sale is not complete.");
require(isCompetitionActive, "The competition is over.");
isCompetitionActive = false;
randomResult = randomness % maxSupply;
payable(ownerOf(randomResult)).transfer(competitionAmount);
}
/**
* @dev Trigger the competition payout (internally).
*/
function requestRandomness() internal nonReentrant {
require(LINK.balanceOf(address(this)) >= oracleFee, "Insufficient LINK balance.");
requestId = requestRandomness(keyHash, oracleFee);
}
/**
* @dev Trigger the competition payout (externally).
*/
function competitionPayout() public payable onlyOwner {
require(isSoldOut(), "The sale is not complete.");
require(isCompetitionActive, "The competition is over.");
requestRandomness();
}
/**
* @dev Return the address of the competition winner (or 0x0 if the competition has not finished).
*/
function competitionWinner() public view virtual returns (address) {
return isCompetitionActive ? address(0) : ownerOf(randomResult);
}
}
// File: src/contracts/TierraPart2.sol
//
pragma solidity ^0.8.6;
// Imports
// Tierra Part 2
contract TierraPart2 is Tierra {
/**
* @dev Constructor
* @param name: The contract name.
* @param symbol: The contract symbol.
* @param maxSupply: The maximum token supply.
* @param baseURI: The base URI for all NFT tokens.
* @param vrfCoordinator: The Chainlink VRF coordinator address for the current network.
* @param linkContractAddress: The Chainlink token's contract address for the current network.
* @param keyHash: The Chainlink oracle's keyhash for the current network.
*/
constructor(
string memory name,
string memory symbol,
uint256 maxSupply,
string memory baseURI,
address vrfCoordinator,
address linkContractAddress,
bytes32 keyHash,
uint256 oracleFee
) Tierra(
name,
symbol,
maxSupply,
baseURI,
true,
vrfCoordinator,
linkContractAddress,
keyHash,
oracleFee
) {
}
}
|
Call base class: ERC721Enumerable._beforeTokenTransfer()./
|
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
| 10,052,390
|
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/Registry.sol
|
Emitted when the address of a contract is changed. id value representing the unique ID tied to the changed contract oldAddress address of the contract before the change newAddress address of the contract after the contract/ Attempted to set the address of a contract that is not registered. id id of the contract that is not registered/ Emitted when depositor privilege changes. depositor depositor address state the new state of the depositor privilege/ The unique ID that the next registered contract will have./ Get the address associated with an id./ In order for an address to make deposits on behalf of users they must be approved./ toggles a depositors ability to deposit into cellars on behalf of users./
|
function setApprovedForDepositOnBehalf(address depositor, bool state) external onlyOwner {
approvedForDepositOnBehalf[depositor] = state;
emit DepositorOnBehalfChanged(depositor, state);
}
| 3,124,253
|
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
import "./mixins/NonTransferrableErc20.sol";
import "./mixins/Vesting.sol";
import "./mixins/Claiming.sol";
import "./mixins/MerkleDistributor.sol";
import "./vendored/mixins/StorageAccessible.sol";
/// @dev The token that manages how the CoW Protocol governance token is
/// distributed to all different types of investors.
/// @title CoW Protocol Virtual Token
/// @author CoW Protocol Developers
contract CowProtocolVirtualToken is
NonTransferrableErc20,
Vesting,
Claiming,
MerkleDistributor,
StorageAccessible
{
string private constant ERC20_SYMBOL = "TESTvCOW";
string private constant ERC20_NAME = "**TEST** CoW Protocol Virtual Token";
constructor(
bytes32 merkleRoot,
address cowToken,
address payable communityFundsTarget,
address investorFundsTarget,
address usdcToken,
uint256 usdcPrice,
address gnoToken,
uint256 gnoPrice,
address wrappedNativeToken,
uint256 nativeTokenPrice,
address teamController
)
NonTransferrableErc20(ERC20_NAME, ERC20_SYMBOL)
Claiming(
cowToken,
communityFundsTarget,
investorFundsTarget,
usdcToken,
usdcPrice,
gnoToken,
gnoPrice,
wrappedNativeToken,
nativeTokenPrice,
teamController
)
MerkleDistributor(merkleRoot)
// solhint-disable-next-line no-empty-blocks
{
}
/// @dev Returns the sum of tokens that are either held as
/// instantlySwappableBalance or will be vested in the future
/// @param user The user for whom the balance is calculated
/// @return Balance of the user
function balanceOf(address user) public view returns (uint256) {
return
instantlySwappableBalance[user] +
fullAllocation[user] -
vestedAllocation[user];
}
/// @dev Returns the balance of a user assuming all vested tokens would
/// have been converted into virtual tokens
/// @param user The user for whom the balance is calculated
/// @return Balance the user would have after calling `swapAll`
function swappableBalanceOf(address user) public view returns (uint256) {
return instantlySwappableBalance[user] + newlyVestedBalance(user);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
import "../vendored/interfaces/IERC20.sol";
/// @dev A contract of an ERC20 token that cannot be transferred.
/// @title Non-Transferrable ERC20
/// @author CoW Protocol Developers
abstract contract NonTransferrableErc20 is IERC20 {
/// @dev The ERC20 name of the token
string public name;
/// @dev The ERC20 symbol of the token
string public symbol;
/// @dev The ERC20 number of decimals of the token
uint8 public constant decimals = 18; // solhint-disable const-name-snakecase
// solhint-disable-next-line no-empty-blocks
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
/// @dev This error is fired when trying to perform an action that is not
/// supported by the contract, like transfers and approvals. These actions
/// will never be supported.
error NotSupported();
/// @dev All types of transfers are permanently disabled.
function transferFrom(
address,
address,
uint256
) public pure returns (bool) {
revert NotSupported();
}
/// @dev All types of transfers are permanently disabled.
function transfer(address, uint256) public pure returns (bool) {
revert NotSupported();
}
/// @dev All types of approvals are permanently disabled to reduce code
/// size.
function approve(address, uint256) public pure returns (bool) {
revert NotSupported();
}
/// @dev Approvals cannot be set, so allowances are always zero.
function allowance(address, address) public pure returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
import "../vendored/libraries/Math.sol";
import "../interfaces/VestingInterface.sol";
/// @dev The vesting logic for distributing the COW token
/// @title Vesting Logic
/// @author CoW Protocol Developers
contract Vesting is VestingInterface {
/// @dev The timestamp of the official vesting start. This value is shared
/// between all participants.
uint256 public immutable vestingStart;
/// @dev How long it will take for all vesting to be completed. It is set to
/// four years.
uint256 public constant VESTING_PERIOD_IN_SECONDS = 4 * 365 days + 1 days;
/// @dev Stores the amount of vesting that the user has already vested.
mapping(address => uint256) public vestedAllocation;
/// @dev Stores the maximum amount of vesting available to each user. This
/// is exactly the total amount of vesting that can be converted after the
/// vesting period is completed.
mapping(address => uint256) public fullAllocation;
/// @dev Stores a bit indicating whether a vesting is cancelable
/// Important: This implementaiton implies that there can not be a
/// cancelable and non-cancelable vesting in parallel
mapping(address => bool) public isCancelable;
/// @dev Event emitted when a new vesting position is added. The amount is
/// the additional amount that can be vested at the end of the
/// claiming period.
event VestingAdded(address indexed user, uint256 amount, bool isCancelable);
/// @dev Event emitted when a vesting position is canceled. The amount is
/// the number of remaining vesting that will be given to the beneficiary.
event VestingStopped(
address indexed user,
address freedVestingBeneficiary,
uint256 amount
);
/// @dev Event emitted when the users claims (also partially) a vesting
/// position.
event Vested(address indexed user, uint256 amount);
/// @dev Error returned when trying to stop a claim that is not cancelable.
error VestingNotCancelable();
constructor() {
vestingStart = block.timestamp; // solhint-disable-line not-rely-on-time
}
/// @inheritdoc VestingInterface
function addVesting(
address user,
uint256 vestingAmount,
bool isCancelableFlag
) internal override {
if (isCancelableFlag) {
// if one cancelable vesting is made, it converts all vestings into cancelable ones
isCancelable[user] = isCancelableFlag;
}
fullAllocation[user] += vestingAmount;
emit VestingAdded(user, vestingAmount, isCancelableFlag);
}
/// @inheritdoc VestingInterface
function shiftVesting(address user, address freedVestingBeneficiary)
internal
override
returns (uint256 accruedVesting)
{
if (!isCancelable[user]) {
revert VestingNotCancelable();
}
accruedVesting = vest(user);
uint256 userFullAllocation = fullAllocation[user];
uint256 userVestedAllocation = vestedAllocation[user];
fullAllocation[user] = 0;
vestedAllocation[user] = 0;
fullAllocation[freedVestingBeneficiary] += userFullAllocation;
vestedAllocation[freedVestingBeneficiary] += userVestedAllocation;
emit VestingStopped(
user,
freedVestingBeneficiary,
userFullAllocation - userVestedAllocation
);
}
/// @inheritdoc VestingInterface
function vest(address user)
internal
override
returns (uint256 newlyVested)
{
newlyVested = newlyVestedBalance(user);
vestedAllocation[user] += newlyVested;
emit Vested(user, newlyVested);
}
/// @dev Assuming no conversions has been done by the user, calculates how
/// much vesting can be converted at this point in time.
/// @param user The user for whom the result is being calculated.
/// @return How much vesting can be converted if no conversions had been
/// done before.
function cumulativeVestedBalance(address user)
public
view
returns (uint256)
{
return
(Math.min(
block.timestamp - vestingStart, // solhint-disable-line not-rely-on-time
VESTING_PERIOD_IN_SECONDS
) * fullAllocation[user]) / (VESTING_PERIOD_IN_SECONDS);
}
/// @dev Calculates how much vesting can be converted at this point in time.
/// Unlike `cumulativeVestedBalance`, this function keeps track of previous
/// conversions.
/// @param user The user for whom the result is being calculated.
/// @return How much vesting can be converted.
function newlyVestedBalance(address user) public view returns (uint256) {
return cumulativeVestedBalance(user) - vestedAllocation[user];
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
import "../vendored/interfaces/IERC20.sol";
import "../vendored/libraries/SafeERC20.sol";
import "../interfaces/ClaimingInterface.sol";
import "../interfaces/VestingInterface.sol";
/// @dev The logic behind the claiming of virtual tokens and the swapping to
/// real tokens.
/// @title COW Virtual Token Claiming Logic
/// @author CoW Protocol Developers
abstract contract Claiming is ClaimingInterface, VestingInterface, IERC20 {
using SafeERC20 for IERC20;
/// @dev Prices are represented as fractions. For readability, the
/// denominator is one unit of the virtual token (assuming it has 18
/// decimals), in this way the numerator of a price is the number of atoms
/// that have the same value as a unit of virtual token.
uint256 internal constant PRICE_DENOMINATOR = 10**18;
/// @dev Price numerator for the COW/USDC price. This is the number of USDC
/// atoms required to obtain a full unit of virtual token from an option.
uint256 public immutable usdcPrice;
/// @dev Price numerator for the COW/GNO price. This is the number of GNO
/// atoms required to obtain a full unit of virtual token from an option.
uint256 public immutable gnoPrice;
/// @dev Price numerator for the COW/native-token price. This is the number
/// of native token wei required to obtain a full unit of virtual token from
/// an option.
uint256 public immutable nativeTokenPrice;
/// @dev The proceeds from selling options to the community will be sent to,
/// this address.
address payable public immutable communityFundsTarget;
/// @dev All proceeds from known investors will be sent to this address.
address public immutable investorFundsTarget;
/// @dev Address of the real COW token. Tokens claimed by this contract can
/// be converted to this token if this contract stores some balance of it.
IERC20 public immutable cowToken;
/// @dev Address of the USDC token. It is a form of payment for investors.
IERC20 public immutable usdcToken;
/// @dev Address of the GNO token. It is a form of payment for users who
/// claim the options derived from holding GNO.
IERC20 public immutable gnoToken;
/// @dev Address of the wrapped native token. It is a form of payment for
/// users who claim the options derived from being users of the CoW
/// Protocol.
IERC20 public immutable wrappedNativeToken;
/// @dev Address representing the CoW Protocol/CowSwap team. It is the only
/// address that is allowed to stop the vesting of a claim, and exclusively
/// for team claims.
address public immutable teamController;
/// @dev Time at which this contract was deployed.
uint256 public immutable deploymentTimestamp;
/// @dev Returns the amount of virtual tokens in existence, including those
/// that have yet to be vested.
uint256 public totalSupply;
/// @dev How many tokens can be immediately swapped in exchange for real
/// tokens for each user.
mapping(address => uint256) public instantlySwappableBalance;
/// @dev Error presented to a user trying to claim virtual tokens after the
/// claiming period has ended.
error ClaimingExpired();
/// @dev Error presented to anyone but the team controller to stop a
/// cancelable vesting position (i.e., only team vesting).
error OnlyTeamController();
/// @dev Error resulting from sending an incorrect amount of native to the
/// contract.
error InvalidNativeTokenAmount();
/// @dev Error caused by an unsuccessful attempt to transfer native tokens.
error FailedNativeTokenTransfer();
/// @dev Error resulting from sending native tokens for a claim that cannot
/// be redeemed with native tokens.
error CannotSendNativeToken();
constructor(
address _cowToken,
address payable _communityFundsTarget,
address _investorFundsTarget,
address _usdcToken,
uint256 _usdcPrice,
address _gnoToken,
uint256 _gnoPrice,
address _wrappedNativeToken,
uint256 _nativeTokenPrice,
address _teamController
) {
cowToken = IERC20(_cowToken);
communityFundsTarget = _communityFundsTarget;
investorFundsTarget = _investorFundsTarget;
usdcToken = IERC20(_usdcToken);
usdcPrice = _usdcPrice;
gnoToken = IERC20(_gnoToken);
gnoPrice = _gnoPrice;
wrappedNativeToken = IERC20(_wrappedNativeToken);
nativeTokenPrice = _nativeTokenPrice;
teamController = _teamController;
// solhint-disable-next-line not-rely-on-time
deploymentTimestamp = block.timestamp;
}
/// @dev Allows the decorated function only to be executed before the
/// contract deployment date plus the input amount of seconds.
/// @param durationSinceDeployment Number of seconds after contract
/// deployment before which the function can be executed anymore. The
/// function reverts afterwards.
modifier before(uint256 durationSinceDeployment) {
// solhint-disable-next-line not-rely-on-time
if (block.timestamp > deploymentTimestamp + durationSinceDeployment) {
revert ClaimingExpired();
}
_;
}
/// @dev The decorated function can only be executed by the team controller.
modifier onlyTeamController() {
if (msg.sender != teamController) {
revert OnlyTeamController();
}
_;
}
/// @inheritdoc ClaimingInterface
function performClaim(
ClaimType claimType,
address payer,
address claimant,
uint256 amount,
uint256 sentNativeTokens
) internal override {
if (claimType == ClaimType.Airdrop) {
claimAirdrop(claimant, amount, sentNativeTokens);
} else if (claimType == ClaimType.GnoOption) {
claimGnoOption(claimant, amount, payer, sentNativeTokens);
} else if (claimType == ClaimType.UserOption) {
claimUserOption(claimant, amount, payer, sentNativeTokens);
} else if (claimType == ClaimType.Investor) {
claimInvestor(claimant, amount, payer, sentNativeTokens);
} else if (claimType == ClaimType.Team) {
claimTeam(claimant, amount, sentNativeTokens);
} else {
// claimType == ClaimType.Advisor
claimAdvisor(claimant, amount, sentNativeTokens);
}
// Each claiming operation results in the creation of `amount` virtual
// tokens.
totalSupply += amount;
emit Transfer(address(0), claimant, amount);
}
/// @dev Stops all vesting claims of a user. This is only applicable for
/// claims that are cancellable, i.e., team claims.
/// @param user The user whose vesting claims should be canceled.
function stopClaim(address user) external onlyTeamController {
uint256 accruedVesting = shiftVesting(user, teamController);
instantlySwappableBalance[user] += accruedVesting;
}
/// @dev Transfers all ETH stored in the contract to the community funds
// target.
function withdrawEth() external {
// We transfer ETH using .call instead of .transfer as not to restrict
// the amount of gas sent to the target address during the transfer.
// This is particularly relevant for sending ETH to smart contracts:
// since EIP 2929, if a contract sends eth using `.transfer` then the
// transaction proposed to the node needs to specify an _access list_,
// which is currently not well supported by some wallet implementations.
// There is no reentrancy risk as this call does not touch any storage
// slot and the contract balance is not used in other logic.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = communityFundsTarget.call{
value: address(this).balance
}("");
if (!success) {
revert FailedNativeTokenTransfer();
}
}
/// @dev Performs an airdrop-type claim for the user.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimAirdrop(
address account,
uint256 amount,
uint256 sentNativeTokens
) private before(6 weeks) {
if (sentNativeTokens != 0) {
revert CannotSendNativeToken();
}
instantlySwappableBalance[account] += amount;
}
/// @dev Claims a Gno option for the user.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user after vesting.
/// @param payer The address that pays the amount required by the claim.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimGnoOption(
address account,
uint256 amount,
address payer,
uint256 sentNativeTokens
) private before(2 weeks) {
if (sentNativeTokens != 0) {
revert CannotSendNativeToken();
}
collectPayment(gnoToken, gnoPrice, payer, communityFundsTarget, amount);
addVesting(account, amount, false);
}
/// @dev Claims a native-token-based option for the user.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user after vesting.
/// @param payer The address that pays the amount required by the claim.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimUserOption(
address account,
uint256 amount,
address payer,
uint256 sentNativeTokens
) private before(2 weeks) {
if (sentNativeTokens != 0) {
collectNativeTokenPayment(amount, sentNativeTokens);
} else {
collectPayment(
wrappedNativeToken,
nativeTokenPrice,
payer,
communityFundsTarget,
amount
);
}
addVesting(account, amount, false);
}
/// @dev Claims an investor option.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user after vesting.
/// @param payer The address that pays the amount required by the claim.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimInvestor(
address account,
uint256 amount,
address payer,
uint256 sentNativeTokens
) private before(2 weeks) {
if (sentNativeTokens != 0) {
revert CannotSendNativeToken();
}
collectPayment(
usdcToken,
usdcPrice,
payer,
investorFundsTarget,
amount
);
addVesting(account, amount, false);
}
/// @dev Claims a team option. Team options are granted without any payment
/// but can be canceled.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user after vesting.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimTeam(
address account,
uint256 amount,
uint256 sentNativeTokens
) private before(6 weeks) {
if (sentNativeTokens != 0) {
revert CannotSendNativeToken();
}
addVesting(account, amount, true);
}
/// @dev Claims an adviser option. Team options are granted without any
/// payment and cannot be canceled.
/// @param account The user for which the claim is performed.
/// @param amount The full amount claimed by the user after vesting.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function claimAdvisor(
address account,
uint256 amount,
uint256 sentNativeTokens
) private before(6 weeks) {
if (sentNativeTokens != 0) {
revert CannotSendNativeToken();
}
addVesting(account, amount, false);
}
/// @dev Executes a transfer from the user to the target. The transfered
/// amount is based on the input COW price and amount of COW bought.
/// @param token The token used for the payment.
/// @param price The number of atoms of the input token that are equivalent
/// to one atom of COW multiplied by PRICE_DENOMINATOR.
/// @param from The address from which to take the funds.
/// @param to The address to which to send the funds.
/// @param amount The amount of COW atoms that will be paid for.
function collectPayment(
IERC20 token,
uint256 price,
address from,
address to,
uint256 amount
) private {
uint256 tokenEquivalent = convertCowAmountAtPrice(amount, price);
token.safeTransferFrom(from, to, tokenEquivalent);
}
/// @dev Transfers native tokens from this contract to the target, assuming
/// that the amount of native tokens sent coincides with the expected amount
/// of native tokens. This amount is based on the price of the native token
/// and amount of COW bought.
/// @param amount The amount of COW atoms that will be paid for.
/// @param sentNativeTokens Amount of ETH sent along to the transaction.
function collectNativeTokenPayment(uint256 amount, uint256 sentNativeTokens)
private
view
{
uint256 nativeTokenEquivalent = convertCowAmountAtPrice(
amount,
nativeTokenPrice
);
if (sentNativeTokens != nativeTokenEquivalent) {
revert InvalidNativeTokenAmount();
}
}
/// @dev Converts input amount in COW token atoms to an amount in token
/// atoms at the specified price.
/// @param amount Amount of tokens to convert.
/// @param price The number of atoms of the input token that are equivalent
/// to one atom of COW *multiplied by PRICE_DENOMINATOR*.
function convertCowAmountAtPrice(uint256 amount, uint256 price)
private
pure
returns (uint256)
{
return (amount * price) / PRICE_DENOMINATOR;
}
/// @dev Converts an amount of (virtual) tokens from this contract to real
/// tokens based on the claims previously performed by the caller.
/// @param amount How many virtual tokens to convert into real tokens.
function swap(uint256 amount) external {
makeVestingSwappable();
_swap(amount);
}
/// @dev Converts all available (virtual) tokens from this contract to real
/// tokens based on the claims previously performed by the caller.
/// @return swappedBalance The full amount that was swapped (i.e., virtual
/// tokens burnt as well as real tokens received).
function swapAll() external returns (uint256 swappedBalance) {
swappedBalance = makeVestingSwappable();
_swap(swappedBalance);
}
/// @dev Transfers real tokens to the message sender and reduces the balance
/// of virtual tokens available. Note that this function assumes that the
/// current contract stores enough real tokens to fulfill this swap request.
/// @param amount How many virtual tokens to convert into real tokens.
function _swap(uint256 amount) private {
instantlySwappableBalance[msg.sender] -= amount;
totalSupply -= amount;
cowToken.safeTransfer(msg.sender, amount);
emit Transfer(msg.sender, address(0), amount);
}
/// @dev Adds the currently vested amount to the immediately swappable
/// balance.
/// @return swappableBalance The maximum balance that can be swapped at
/// this point in time by the caller.
function makeVestingSwappable() private returns (uint256 swappableBalance) {
swappableBalance =
instantlySwappableBalance[msg.sender] +
vest(msg.sender);
instantlySwappableBalance[msg.sender] = swappableBalance;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
// This contract is based on Uniswap's MekleDistributor, which can be found at:
// https://github.com/Uniswap/merkle-distributor/blob/0d478d722da2e5d95b7292fd8cbdb363d98e9a93/contracts/MerkleDistributor.sol
//
// The changes between the original contract and this are:
// - the claim function doesn't trigger a transfer on a successful proof, but
// it executes a dedicated (virtual) function.
// - added a claimMany function for bundling multiple claims in a transaction
// - supported sending an amount of native tokens along with the claim
// - added the option of claiming less than the maximum amount
// - gas optimizations in the packing and unpacking of the claimed bit
// - bumped Solidity version
// - code formatting
pragma solidity ^0.8.10;
import "../vendored/interfaces/IERC20.sol";
import "../vendored/libraries/MerkleProof.sol";
import "../interfaces/ClaimingInterface.sol";
abstract contract MerkleDistributor is ClaimingInterface {
bytes32 public immutable merkleRoot;
/// @dev Event fired if a claim was successfully performed.
event Claimed(
uint256 index,
ClaimType claimType,
address claimant,
uint256 claimableAmount,
uint256 claimedAmount
);
/// @dev Error caused by a user trying to call the claim function for a
/// claim that has already been used before.
error AlreadyClaimed();
/// @dev Error caused by a user trying to claim a larger amount than the
/// maximum allowed in the claim.
error ClaimingMoreThanMaximum();
/// @dev Error caused by the caller trying to perform a partial claim while
/// not being the owner of the claim.
error OnlyOwnerCanClaimPartially();
/// @dev Error caused by calling the claim function with an invalid proof.
error InvalidProof();
/// @dev Error caused by calling claimMany with a transaction value that is
/// different from the required one.
error InvalidNativeTokenValue();
/// @dev Packed array of booleans that stores if a claim is available.
mapping(uint256 => uint256) private claimedBitMap;
constructor(bytes32 merkleRoot_) {
merkleRoot = merkleRoot_;
}
/// @dev Checks if the claim at the provided index has already been claimed.
/// @param index The index to check.
/// @return Whether the claim at the given index has already been claimed.
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index >> 8;
uint256 claimedBitIndex = index & 0xff;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask != 0;
}
/// @dev Mark the provided index as having been claimed.
/// @param index The index that was claimed.
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index >> 8;
uint256 claimedBitIndex = index & 0xff;
claimedBitMap[claimedWordIndex] =
claimedBitMap[claimedWordIndex] |
(1 << claimedBitIndex);
}
/// @dev This function verifies the provided input proof based on the
/// provided input. If the proof is valid, the function [`performClaim`] is
/// called for the claimed amount.
/// @param index The index that identifies the input claim.
/// @param claimType See [`performClaim`].
/// @param claimant See [`performClaim`].
/// @param claimableAmount The maximum amount that the claimant can claim
/// for this claim. Should not be smaller than claimedAmount.
/// @param claimedAmount See [`performClaim`].
/// @param merkleProof A proof that the input claim belongs to the unique
/// Merkle root associated to this contract.
function claim(
uint256 index,
ClaimType claimType,
address claimant,
uint256 claimableAmount,
uint256 claimedAmount,
bytes32[] calldata merkleProof
) external payable {
_claim(
index,
claimType,
claimant,
claimableAmount,
claimedAmount,
merkleProof,
msg.value
);
}
/// @dev This function verifies and executes multiple claims in the same
/// transaction.
/// @param indices A vector of indices. See [`claim`] for details.
/// @param claimTypes A vector of claim types. See [`performClaim`] for
/// details.
/// @param claimants A vector of claimants. See [`performClaim`] for
/// details.
/// @param claimableAmounts A vector of claimable amounts. See [`claim`] for
/// details.
/// @param claimedAmounts A vector of claimed amounts. See [`performClaim`]
/// for details.
/// @param merkleProofs A vector of merkle proofs. See [`claim`] for
/// details.
/// @param sentNativeTokens A vector of native token amounts. See
/// [`performClaim`] for details.
function claimMany(
uint256[] memory indices,
ClaimType[] memory claimTypes,
address[] calldata claimants,
uint256[] calldata claimableAmounts,
uint256[] calldata claimedAmounts,
bytes32[][] calldata merkleProofs,
uint256[] calldata sentNativeTokens
) external payable {
uint256 sumSentNativeTokens;
for (uint256 i = 0; i < indices.length; i++) {
sumSentNativeTokens += sentNativeTokens[i];
_claim(
indices[i],
claimTypes[i],
claimants[i],
claimableAmounts[i],
claimedAmounts[i],
merkleProofs[i],
sentNativeTokens[i]
);
}
if (sumSentNativeTokens != msg.value) {
revert InvalidNativeTokenValue();
}
}
/// @dev This function verifies the provided input proof based on the
/// provided input. If the proof is valid, the function [`performClaim`] is
/// called for the claimed amount.
/// @param index See [`claim`].
/// @param claimType See [`performClaim`].
/// @param claimant See [`performClaim`].
/// @param claimableAmount See [`claim`].
/// @param claimedAmount See [`performClaim`].
/// @param merkleProof See [`claim`].
/// @param sentNativeTokens See [`performClaim`].
function _claim(
uint256 index,
ClaimType claimType,
address claimant,
uint256 claimableAmount,
uint256 claimedAmount,
bytes32[] calldata merkleProof,
uint256 sentNativeTokens
) private {
if (isClaimed(index)) {
revert AlreadyClaimed();
}
if (claimedAmount > claimableAmount) {
revert ClaimingMoreThanMaximum();
}
if ((claimedAmount < claimableAmount) && (msg.sender != claimant)) {
revert OnlyOwnerCanClaimPartially();
}
// Note: all types used inside `encodePacked` should have fixed length,
// otherwise the same proof could be used in different claims.
bytes32 node = keccak256(
abi.encodePacked(index, claimType, claimant, claimableAmount)
);
if (!MerkleProof.verify(merkleProof, merkleRoot, node)) {
revert InvalidProof();
}
_setClaimed(index);
performClaim(
claimType,
msg.sender,
claimant,
claimedAmount,
sentNativeTokens
);
emit Claimed(
index,
claimType,
claimant,
claimableAmount,
claimedAmount
);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
// Vendored from Gnosis utility contracts, see:
// <https://raw.githubusercontent.com/gnosis/gp-v2-contracts/40c349d52d14f8f3c9f787fe2fca5a496bb10ea9/src/contracts/mixins/StorageAccessible.sol>
// The following changes were made:
// - Modified Solidity version
// - Formatted code
pragma solidity ^0.8.10;
/// @title ViewStorageAccessible - Interface on top of StorageAccessible base class to allow simulations from view functions
interface ViewStorageAccessible {
/**
* @dev Same as `simulateDelegatecall` on StorageAccessible. Marked as view so that it can be called from external contracts
* that want to run simulations from within view functions. Will revert if the invoked simulation attempts to change state.
*/
function simulateDelegatecall(
address targetContract,
bytes memory calldataPayload
) external view returns (bytes memory);
/**
* @dev Same as `getStorageAt` on StorageAccessible. This method allows reading aribtrary ranges of storage.
*/
function getStorageAt(uint256 offset, uint256 length)
external
view
returns (bytes memory);
}
/// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
contract StorageAccessible {
/**
* @dev Reads `length` bytes of storage in the currents contract
* @param offset - the offset in the current contract's storage in words to start reading from
* @param length - the number of words (32 bytes) of data to read
* @return the bytes that were read.
*/
function getStorageAt(uint256 offset, uint256 length)
external
view
returns (bytes memory)
{
bytes memory result = new bytes(length * 32);
for (uint256 index = 0; index < length; index++) {
// solhint-disable-next-line no-inline-assembly
assembly {
let word := sload(add(offset, index))
mstore(add(add(result, 0x20), mul(index, 0x20)), word)
}
}
return result;
}
/**
* @dev Performs a delegetecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static). Catches revert and returns encoded result as bytes.
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateDelegatecall(
address targetContract,
bytes memory calldataPayload
) public returns (bytes memory response) {
bytes memory innerCall = abi.encodeWithSelector(
this.simulateDelegatecallInternal.selector,
targetContract,
calldataPayload
);
// solhint-disable-next-line avoid-low-level-calls
(, response) = address(this).call(innerCall);
bool innerSuccess = response[response.length - 1] == 0x01;
setLength(response, response.length - 1);
if (innerSuccess) {
return response;
} else {
revertWith(response);
}
}
/**
* @dev Performs a delegetecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static). Returns encoded result as revert message
* concatenated with the success flag of the inner call as a last byte.
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateDelegatecallInternal(
address targetContract,
bytes memory calldataPayload
) external returns (bytes memory response) {
bool success;
// solhint-disable-next-line avoid-low-level-calls
(success, response) = targetContract.delegatecall(calldataPayload);
revertWith(abi.encodePacked(response, success));
}
function revertWith(bytes memory response) internal pure {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(response, 0x20), mload(response))
}
}
function setLength(bytes memory buffer, uint256 length) internal pure {
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(buffer, length)
}
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin Contracts v4.4.0, see:
// <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/token/ERC20/IERC20.sol>
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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
// Vendored from OpenZeppelin Contracts v4.4.0, see:
// <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/utils/math/Math.sol>
// OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
/// @dev The contract functions that are shared between the `Vesting` and
/// `Claiming` contracts. The two components are handled and tested
/// separately and are linked to each other by the functions in this contract.
/// This contracs is for all intents and purposes an interface, however actual
/// interfaces cannot declare internal functions.
/// @title COW token vesting interface.
/// @author CoW Protocol Developers
abstract contract VestingInterface {
/// @dev Adds an amount that will be vested over time.
/// Should be called from the parent contract on redeeming a vested claim.
/// @param user The user for whom the vesting is performed.
/// @param vestingAmount The (added) amount to be vested in time.
/// @param isCancelableFlag Flag whether the vesting is cancelable
function addVesting(
address user,
uint256 vestingAmount,
bool isCancelableFlag
) internal virtual;
/// @dev Computes the current vesting from the total vested amount and marks
/// that amount as converted. This is called by the parent contract every
/// time virtual tokens from a vested claim are swapped into real tokens.
/// @param user The user for which the amount is vested.
/// @return Amount converted.
function vest(address user) internal virtual returns (uint256);
/// @dev Transfers a cancelable vesting of a user to another address.
/// Returns the amount of token that is not yet converted.
/// @param user The user for whom the vesting is removed.
/// @param freedVestingBeneficiary The address to which to assign the amount
/// that remains to be vested.
/// @return accruedVesting The total number of tokens that remain to be
/// converted
function shiftVesting(address user, address freedVestingBeneficiary)
internal
virtual
returns (uint256 accruedVesting);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
// Vendored from GPv2 contracts v1.1.2, see:
// <https://raw.githubusercontent.com/gnosis/gp-v2-contracts/7fb88982021e9a274d631ffb598694e6d9b30089/src/contracts/libraries/GPv2SafeERC20.sol>
// The following changes were made:
// - Bumped up Solidity version and checked that the assembly is still valid.
// - Use own vendored IERC20 instead of custom implementation.
// - Removed "GPv2" from contract name.
// - Modified revert messages, including length.
pragma solidity ^0.8.10;
import "../interfaces/IERC20.sol";
/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library
/// @author Gnosis Developers
/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract.
library SafeERC20 {
/// @dev Wrapper around a call to the ERC20 function `transfer` that reverts
/// also when the token returns `false`.
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transfer.selector;
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 36), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "SafeERC20: failed transfer");
}
/// @dev Wrapper around a call to the ERC20 function `transferFrom` that
/// reverts also when the token returns `false`.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transferFrom.selector;
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 68), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "SafeERC20: failed transferFrom");
}
/// @dev Verifies that the last return was a successful `transfer*` call.
/// This is done by checking that the return data is either empty, or
/// is a valid ABI encoded boolean.
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
// NOTE: Inspecting previous return data requires assembly. Note that
// we write the return data to memory 0 in the case where the return
// data size is 32, this is OK since the first 64 bytes of memory are
// reserved by Solidy as a scratch space that can be used within
// assembly blocks.
// <https://docs.soliditylang.org/en/v0.8.10/internals/layout_in_memory.html>
// solhint-disable-next-line no-inline-assembly
assembly {
/// @dev Revert with an ABI encoded Solidity error with a message
/// that fits into 32-bytes.
///
/// An ABI encoded Solidity error has the following memory layout:
///
/// ------------+----------------------------------
/// byte range | value
/// ------------+----------------------------------
/// 0x00..0x04 | selector("Error(string)")
/// 0x04..0x24 | string offset (always 0x20)
/// 0x24..0x44 | string length
/// 0x44..0x64 | string value, padded to 32-bytes
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
// Non-standard ERC20 transfer without return.
case 0 {
// NOTE: When the return data size is 0, verify that there
// is code at the address. This is done in order to maintain
// compatibility with Solidity calling conventions.
// <https://docs.soliditylang.org/en/v0.8.10/control-structures.html#external-function-calls>
if iszero(extcodesize(token)) {
revertWithMessage(25, "SafeERC20: not a contract")
}
success := 1
}
// Standard ERC20 transfer returning boolean success value.
case 32 {
returndatacopy(0, 0, returndatasize())
// NOTE: For ABI encoding v1, any non-zero value is accepted
// as `true` for a boolean. In order to stay compatible with
// OpenZeppelin's `SafeERC20` library which is known to work
// with the existing ERC20 implementation we care about,
// make sure we return success for any non-zero return value
// from the `transfer*` call.
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(30, "SafeERC20: bad transfer result")
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
/// @dev The contract functions that are shared between the `Claiming` and
/// `MerkleDistributor` contracts. The two components are handled and tested
/// separately and are linked to each other by the functions in this contract.
/// This contracs is for all intents and purposes an interface, however actual
/// interfaces cannot declare internal functions.
/// @title COW token claiming interface.
/// @author CoW Protocol Developers
abstract contract ClaimingInterface {
/// @dev Exhaustive list of the different branches of the claiming logic.
enum ClaimType {
Airdrop,
GnoOption,
UserOption,
Investor,
Team,
Advisor
}
/// @dev This function is executed when a valid proof of the claim is
/// provided and executes all steps required for each claim type.
/// @param claimType Which claim will be performed. See [`ClaimType`] for
/// an exausting list.
/// @param payer The address that will pay if the claim to be performed
/// requires a payment.
/// @param claimant The account to which the claim is assigned and which
/// will receive the corresponding virtual tokens.
/// @param claimedAmount The amount that the user decided to claim (after
/// vesting if it applies).
/// @param sentNativeTokens The amount of native tokens that the user sent
/// along with the transaction.
function performClaim(
ClaimType claimType,
address payer,
address claimant,
uint256 claimedAmount,
uint256 sentNativeTokens
) internal virtual;
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin Contracts v4.4.0, see:
// <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/utils/cryptography/MerkleProof.sol>
// OpenZeppelin Contracts v4.4.0 (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;
}
}
|
Checks if the claim at the provided index has already been claimed. index The index to check. return Whether the claim at the given index has already been claimed.
|
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index >> 8;
uint256 claimedBitIndex = index & 0xff;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask != 0;
}
| 12,096,482
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IStrategy {
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external;
function emergencyWithdraw() external;
function updateMinTokensToReinvest(uint newValue) external;
function updateAdminFee(uint newValue) external;
function updateDevFee(uint newValue) external;
function updateDepositsEnabled(bool newValue) external;
function updateMaxTokensToDepositWithoutReinvest(uint newValue) external;
function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external;
function updateReinvestReward(uint newValue) external;
function recoverERC20(address tokenAddress, uint tokenAmount) external;
function recoverAVAX(uint amount) external;
function setAllowances() external;
function allowDepositor(address depositor) external;
function removeDepositor(address depositor) external;
}
/**
* @notice A generic timelock for YakStrategies
* @dev Ensure function is supported by strategy
*/
contract YakTimelockForDexStrategyV3 {
uint public constant timelockLengthForAssetRecovery = 2 days;
uint public constant timelockLengthForOwnershipTransfer = 4 days;
uint public constant timelockLengthForFeeChanges = 8 hours;
address public immutable manager;
address public immutable feeCollector;
mapping(address => address) public pendingOwners;
mapping(address => uint) public pendingAdminFees;
mapping(address => uint) public pendingDevFees;
mapping(address => uint) public pendingReinvestRewards;
mapping(address => address) public pendingTokenAddressesToRecover;
mapping(address => uint) public pendingTokenAmountsToRecover;
mapping(address => uint) public pendingAVAXToRecover;
event ProposeOwner(address indexed strategy, address indexed proposedValue, uint timelock);
event ProposeAdminFee(address indexed strategy, uint proposedValue, uint timelock);
event ProposeDevFee(address indexed strategy, uint proposedValue, uint timelock);
event ProposeReinvestReward(address indexed strategy, uint proposedValue, uint timelock);
event ProposeRecovery(address indexed strategy, address indexed proposedToken, uint proposedValue, uint timelock);
event SetOwner(address indexed strategy, address indexed newValue);
event SetAdminFee(address indexed strategy, uint newValue);
event SetDevFee(address indexed strategy, uint newValue);
event SetReinvestReward(address indexed strategy, uint newValue);
event SetMinTokensToReinvest(address indexed strategy, uint newValue);
event SetDepositsEnabled(address indexed strategy, bool newValue);
event Sweep(address indexed token, uint amount);
event Recover(address indexed strategy, address indexed token, uint amount);
event EmergencyWithdraw(address indexed strategy);
event SetAllowances(address indexed strategy);
event SetMaxTokensToDepositWithoutReinvest(address indexed strategy, uint newValue);
event AllowDepositor(address indexed strategy, address indexed depositor);
event RemoveDepositor(address indexed strategy, address indexed depositor);
enum Functions {
renounceOwnership,
transferOwnership,
emergencyWithdraw,
updateMinTokensToReinvest,
updateAdminFee,
updateDevFee,
updateReinvestReward,
recoverERC20,
recoverAVAX
}
mapping(address => mapping(Functions => uint)) public timelock;
constructor() {
manager = msg.sender;
feeCollector = msg.sender;
}
// Modifiers
/**
* @notice Restrict to `manager`
* @dev To change manager, deploy new timelock and transfer strategy ownership
*/
modifier onlyManager {
require(msg.sender == manager);
_;
}
/**
* @notice Restrict to `feeCollector`
* @dev To change feeCollector, deploy new timelock and transfer strategy ownership
*/
modifier onlyFeeCollector {
require(msg.sender == feeCollector);
_;
}
/**
* @notice Set timelock when changing pending values
* @param _strategy address
* @param _fn Function enum value
* @param timelockLength in seconds
*/
modifier setTimelock(address _strategy, Functions _fn, uint timelockLength) {
timelock[_strategy][_fn] = block.timestamp + timelockLength;
_;
}
/**
* @notice Enforce timelock for a given function
* @dev Ends execution by resetting timelock to avoid replay
* @param _strategy address
* @param _fn Function enum value
*/
modifier enforceTimelock(address _strategy, Functions _fn) {
require(timelock[_strategy][_fn] != 0 && timelock[_strategy][_fn] <= block.timestamp, "YakTimelockManager::enforceTimelock");
_;
timelock[_strategy][_fn] = 0;
}
/**
* @notice Sweep tokens from the timelock to `feeCollector`
* @dev The timelock contract may receive assets from both revenue and asset recovery.
* @dev The sweep function is NOT timelocked, because recovered assets must go through separate timelock functions.
* @param tokenAddress address
* @param tokenAmount amount
*/
function sweepTokens(address tokenAddress, uint tokenAmount) external onlyFeeCollector {
require(tokenAmount > 0, "YakTimelockManager::sweepTokens, amount too low");
require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount), "YakTimelockManager::sweepTokens, transfer failed");
emit Sweep(tokenAddress, tokenAmount);
}
/**
* @notice Sweep AVAX from the timelock to the `feeCollector` address
* @dev The timelock contract may receive assets from both revenue and asset recovery.
* @dev The sweep function is NOT timelocked, because recovered assets must go through separate timelock functions.
* @param amount amount
*/
function sweepAVAX(uint amount) external onlyFeeCollector {
require(amount > 0, 'YakTimelockManager::sweepAVAX, amount too low');
msg.sender.transfer(amount);
emit Sweep(address(0), amount);
}
// Functions with timelocks
/**
* @notice Pass new value of `owner` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingOwner new value
*/
function proposeOwner(address _strategy, address _pendingOwner) external onlyManager
setTimelock(_strategy, Functions.transferOwnership, timelockLengthForOwnershipTransfer) {
pendingOwners[_strategy] = _pendingOwner;
emit ProposeOwner(_strategy, _pendingOwner, timelock[_strategy][Functions.transferOwnership]);
}
/**
* @notice Set new value of `owner` and resets timelock
* @dev This can be called by anyone
* @param _strategy address
*/
function setOwner(address _strategy) external
enforceTimelock(_strategy, Functions.transferOwnership) {
IStrategy(_strategy).transferOwnership(pendingOwners[_strategy]);
emit SetOwner(_strategy, pendingOwners[_strategy]);
pendingOwners[_strategy] = address(0);
}
/**
* @notice Pass new value of `adminFee` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingAdminFee new value
*/
function proposeAdminFee(address _strategy, uint _pendingAdminFee) external onlyManager
setTimelock(_strategy, Functions.updateAdminFee, timelockLengthForFeeChanges) {
pendingAdminFees[_strategy] = _pendingAdminFee;
emit ProposeAdminFee(_strategy, _pendingAdminFee, timelock[_strategy][Functions.updateAdminFee]);
}
/**
* @notice Set new value of `adminFee` and reset timelock
* @dev This can be called by anyone
* @param _strategy address
*/
function setAdminFee(address _strategy) external
enforceTimelock(_strategy, Functions.updateAdminFee) {
IStrategy(_strategy).updateAdminFee(pendingAdminFees[_strategy]);
emit SetAdminFee(_strategy, pendingAdminFees[_strategy]);
pendingAdminFees[_strategy] = 0;
}
/**
* @notice Pass new value of `devFee` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingDevFee new value
*/
function proposeDevFee(address _strategy, uint _pendingDevFee) external onlyManager
setTimelock(_strategy, Functions.updateDevFee, timelockLengthForFeeChanges) {
pendingDevFees[_strategy] = _pendingDevFee;
emit ProposeDevFee(_strategy, _pendingDevFee, timelock[_strategy][Functions.updateDevFee]);
}
/**
* @notice Set new value of `devFee` and reset timelock
* @dev This can be called by anyone
* @param _strategy address
*/
function setDevFee(address _strategy) external
enforceTimelock(_strategy, Functions.updateDevFee) {
IStrategy(_strategy).updateDevFee(pendingDevFees[_strategy]);
emit SetDevFee(_strategy, pendingDevFees[_strategy]);
pendingDevFees[_strategy] = 0;
}
/**
* @notice Pass new value of `reinvestReward` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingReinvestReward new value
*/
function proposeReinvestReward(address _strategy, uint _pendingReinvestReward) external onlyManager
setTimelock(_strategy, Functions.updateReinvestReward, timelockLengthForFeeChanges) {
pendingReinvestRewards[_strategy] = _pendingReinvestReward;
emit ProposeReinvestReward(_strategy, _pendingReinvestReward, timelock[_strategy][Functions.updateReinvestReward]);
}
/**
* @notice Set new value of `reinvestReward` and reset timelock
* @dev This can be called by anyone
* @param _strategy address
*/
function setReinvestReward(address _strategy) external
enforceTimelock(_strategy, Functions.updateReinvestReward) {
IStrategy(_strategy).updateReinvestReward(pendingReinvestRewards[_strategy]);
emit SetReinvestReward(_strategy, pendingReinvestRewards[_strategy]);
pendingReinvestRewards[_strategy] = 0;
}
/**
* @notice Pass values for `recoverERC20` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingTokenAddressToRecover address
* @param _pendingTokenAmountToRecover amount
*/
function proposeRecoverERC20(address _strategy, address _pendingTokenAddressToRecover, uint _pendingTokenAmountToRecover) external onlyManager
setTimelock(_strategy, Functions.recoverERC20, timelockLengthForAssetRecovery) {
pendingTokenAddressesToRecover[_strategy] = _pendingTokenAddressToRecover;
pendingTokenAmountsToRecover[_strategy] = _pendingTokenAmountToRecover;
emit ProposeRecovery(_strategy, _pendingTokenAddressToRecover, _pendingTokenAmountToRecover, timelock[_strategy][Functions.recoverERC20]);
}
/**
* @notice Call `recoverERC20` and reset timelock
* @dev This can be called by anyone
* @dev Recoverd funds are collected to this timelock and may be swept
* @param _strategy address
*/
function setRecoverERC20(address _strategy) external
enforceTimelock(_strategy, Functions.recoverERC20) {
IStrategy(_strategy).recoverERC20(pendingTokenAddressesToRecover[_strategy], pendingTokenAmountsToRecover[_strategy]);
emit Recover(_strategy, pendingTokenAddressesToRecover[_strategy], pendingTokenAmountsToRecover[_strategy]);
pendingTokenAddressesToRecover[_strategy] = address(0);
pendingTokenAmountsToRecover[_strategy] = 0;
}
/**
* @notice Pass values for `recoverAVAX` through timelock
* @dev Restricted to `manager` to avoid griefing
* @dev Resets timelock duration through modifier
* @param _strategy address
* @param _pendingAVAXToRecover amount
*/
function proposeRecoverAVAX(address _strategy, uint _pendingAVAXToRecover) external onlyManager
setTimelock(_strategy, Functions.recoverAVAX, timelockLengthForAssetRecovery) {
pendingAVAXToRecover[_strategy] = _pendingAVAXToRecover;
emit ProposeRecovery(_strategy, address(0), _pendingAVAXToRecover, timelock[_strategy][Functions.recoverAVAX]);
}
/**
* @notice Call `recoverAVAX` and reset timelock
* @dev This can be called by anyone
* @dev Recoverd funds are collected to this timelock and may be swept
* @param _strategy address
*/
function setRecoverAVAX(address _strategy) external
enforceTimelock(_strategy, Functions.recoverAVAX) {
IStrategy(_strategy).recoverAVAX(pendingAVAXToRecover[_strategy]);
emit Recover(_strategy, address(0), pendingAVAXToRecover[_strategy]);
pendingAVAXToRecover[_strategy] = 0;
}
// Functions without timelocks
/**
* @notice Set new value of `minTokensToReinvest`
* @dev Restricted to `manager` to avoid griefing
* @param _strategy address
* @param newValue min tokens
*/
function setMinTokensToReinvest(address _strategy, uint newValue) external onlyManager {
IStrategy(_strategy).updateMinTokensToReinvest(newValue);
emit SetMinTokensToReinvest(_strategy, newValue);
}
/**
* @notice Set new value of `maxTokensToDepositWithoutReinvest`
* @dev Restricted to `manager` to avoid griefing
* @param _strategy address
* @param newValue max tokens
*/
function setMaxTokensToDepositWithoutReinvest(address _strategy, uint newValue) external onlyManager {
IStrategy(_strategy).updateMaxTokensToDepositWithoutReinvest(newValue);
emit SetMaxTokensToDepositWithoutReinvest(_strategy, newValue);
}
/**
* @notice Enable/disable deposits (After YakStrategy)
* @param _strategy address
* @param newValue bool
*/
function setDepositsEnabled(address _strategy, bool newValue) external onlyManager {
IStrategy(_strategy).updateDepositsEnabled(newValue);
emit SetDepositsEnabled(_strategy, newValue);
}
/**
* @notice Rescues deployed assets to the strategy contract (Before YakStrategy)
* @dev Restricted to `manager` to avoid griefing
* @param _strategy address
*/
function emergencyWithdraw(address _strategy) external onlyManager {
IStrategy(_strategy).emergencyWithdraw();
emit EmergencyWithdraw(_strategy);
}
/**
* @notice Rescues deployed assets to the strategy contract (After YakStrategy)
* @dev Restricted to `manager` to avoid griefing
* @param _strategy address
* @param minReturnAmountAccepted amount
* @param disableDeposits bool
*/
function rescueDeployedFunds(address _strategy, uint minReturnAmountAccepted, bool disableDeposits) external onlyManager {
IStrategy(_strategy).rescueDeployedFunds(minReturnAmountAccepted, disableDeposits);
emit EmergencyWithdraw(_strategy);
}
/**
* @notice Sets token approvals
* @dev Restricted to `manager` to avoid griefing
* @param _strategy address
*/
function setAllowances(address _strategy) external onlyManager {
IStrategy(_strategy).setAllowances();
emit SetAllowances(_strategy);
}
/**
* @notice Add to list of allowed depositors
* @param _strategy address
* @param depositor address
*/
function allowDepositor(address _strategy, address depositor) external onlyManager {
IStrategy(_strategy).allowDepositor(depositor);
emit AllowDepositor(_strategy, depositor);
}
/**
* @notice Remove from list of allowed depositors
* @param _strategy address
* @param depositor address
*/
function removeDepositor(address _strategy, address depositor) external onlyManager {
IStrategy(_strategy).removeDepositor(depositor);
emit RemoveDepositor(_strategy, depositor);
}
}
|
Add to list of allowed depositors _strategy address depositor address/
|
function allowDepositor(address _strategy, address depositor) external onlyManager {
IStrategy(_strategy).allowDepositor(depositor);
emit AllowDepositor(_strategy, depositor);
}
| 6,461,579
|
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "../interfaces/ILottary.sol";
import "../interfaces/IZep.sol";
import "../interfaces/IWinnerNFT.sol";
import "../interfaces/IFomoRouter.sol";
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (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);
}
interface ICakeIRouter {
function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable;
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
}
contract Lottary is ILottary {
address WBNB ;
// address WBNB;
// address ZEPPELIN__ADDRESS ;
address deployer;
IFomoRouterV1 internal fomoRouter;
IWinnerNFT public winnerNFT;
ICakeIRouter internal constant cakeRouter;
// ICakeIRouter internal constant cakeRouter;
uint MAX_REFERRALS = 30;
// VARS
address[] participants;
mapping(address => uint) public walletToEntries;
mapping(address => uint) public walletToBnbSpent;
mapping(address => uint) public walletToReferralTimes;
uint256 totalBNBCollected;
uint256 startBlock;
uint256 finishBlock;
uint256 issueId;
mapping(uint256 => address[4]) public historyWinners;
// issueId => (place => amounts) [issueId][place].push()
mapping(uint256 => mapping(uint => uint256[])) public historyBasketAmounts;
mapping(uint256 => address[]) public historyBasketTokens;
// sorted
address [4] public winningAddresses;
uint256[4] public winningIndexes;
uint256 public lastTimestamp;
uint[] rewardDistribution;
// EVENTS
// TODO: add events
event Entry(address indexed user, uint256 indexed amount);
event WinnersChosen(uint256 indexed issueId, address[4] winningAddresses);
event Reset(uint256 indexed issueId);
constructor(
address _winnerNFT,
address fomoRouterAddr
) {
deployer = msg.sender;
lastTimestamp = block.timestamp;
winnerNFT = IWinnerNFT(_winnerNFT);
fomoRouter = IFomoRouterV1(fomoRouterAddr);
fomoRouter.registerNewLottary(address(this));
// Default percentages
rewardDistribution.push(5000);
rewardDistribution.push(2500);
rewardDistribution.push(2500);
}
modifier onlyOwnerAndRouter {
require(msg.sender == deployer || msg.sender == address(fomoRouter));
_;
}
function isContract(address _addr) internal view returns (bool isContractR){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
/* ENTER */
function enter(address _sender, uint _amount, address _referredBy) external override payable {
console.log("CALLED enter!", _amount, _amount == 1e18);
require(isContract(_sender) == false, "No contracts can enter");
// TODO: needed ?
require(_sender != address(0), "Null addr");
require(
_amount % 5 == 0
&& ((_amount >= 5e16 && _amount <= 5e17) || _amount == 1e18 || _amount == 5e18 || _amount == 1e19),
"Please Enter Valid Amount");
console.log("CALLED enter 2!");
console.log("_amount:", _amount);
uint256 entryTimes = 0;
if (_amount == 5e16) entryTimes = 1;
if (_amount == 10e16) entryTimes = 2;
if (_amount == 15e16) entryTimes = 3;
if (_amount == 20e16) entryTimes = 4;
if (_amount == 25e16) entryTimes = 6;
if (_amount == 30e16) entryTimes = 8;
if (_amount == 35e16) entryTimes = 10;
if (_amount == 40e16) entryTimes = 12;
if (_amount == 45e16) entryTimes = 14;
if (_amount == 5e17) entryTimes = 16;
if (_amount == 1e18) entryTimes = 40;
if (_amount == 5e18) entryTimes = 240;
if (_amount == 1e19) entryTimes = 600;
for (uint i = 0; i < entryTimes; i++) {
participants.push(_sender);
}
// Referrals
if (_referredBy != address(0)) {
// TODO: Min Amount for referral elligibile =
// TODO: a _referredBy divHolder = more tickets
if (walletToEntries[_sender] == 0 && walletToEntries[_referredBy] > 0) {
if (walletToReferralTimes[_referredBy] < MAX_REFERRALS) {
walletToReferralTimes[_referredBy]++;
participants.push(_referredBy);
}
}
}
relayToRouter(_amount, msg.sender);
totalBNBCollected += _amount;
walletToEntries[_sender] += entryTimes;
walletToBnbSpent[_sender] += _amount;
}
// TODO: Entry with zep = +10% tickets
// TODO: SLIPPAGE
// todo: refund bnb which is left
function swapTokensForBnbAndEnter(address token, uint256 bnbAmount) external override {
// uTrade swap one day
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(WBNB);
// TODO: fee
uint256[] memory amounts = cakeRouter.swapTokensForExactETH(bnbAmount, 0, path, address(this), block.timestamp);
this.enter(msg.sender, amounts[1], address(0));
}
// function getAmountsOut(address token, uint256 amount) public view returns (uint256, uint256) {
// address[] memory path = new address[](2);
// path[0] = address(WBNB);
// path[1] = address(token);
//
// return cakeRouter.getAmountsOut(amount, path)[1];
// }
function relayToRouter(uint256 bnbAmount, address participant) internal {
fomoRouter.invest{value : bnbAmount}(issueId, participant);
}
/* START FINISH */
function start(uint blockPeriod) external override {
require(msg.sender == deployer, "Not ownerr");
require(startBlock == 0 && finishBlock == 0, "Must be clear to start");
startBlock = block.number;
finishBlock = startBlock + blockPeriod;
issueId = startBlock;
}
function finish(uint256[] calldata _externalRandomNumbers, address[] calldata _tokensInBasket) external override onlyOwnerAndRouter {
require(startBlock != 0 && finishBlock != 0, "Lottary Not Started !");
// require(block.number > finishBlock, "Not time yet");
require(participants.length >= 4, "Not enough participants");
distributeReward(_externalRandomNumbers, _tokensInBasket);
startBlock = 0;
finishBlock = 0;
lastTimestamp = block.timestamp;
for (uint i = 0; i < participants.length; i++) {
delete walletToEntries[participants[i]];
delete walletToBnbSpent[participants[i]];
// TODO: check if this is the most efficient way ? (won't it always keep the memory)
}
delete participants;
totalBNBCollected = 0;
}
function distributeReward(uint256[] calldata _externalRandomNumbers, address[] calldata _tokensInBasket) internal {
// uint256 winIndex = this.generateRandom(participants.length / 1e18, address(this).balance / 1e18, block.difficulty / 1e18);
bytes32 _structHash;
uint256 randomNumber;
bytes32 _blockhash = blockhash(block.number - 1);
uint256 length = participants.length;
console.log("CALLED distributeReward!", length);
// waste some gas fee here
for (uint i = 0; i < 9; i++) {
getTotalParticipants(issueId);
}
uint256 gasleft = gasleft();
uint256[] memory outherFactor = new uint256[](4);
outherFactor[0] = block.difficulty;
outherFactor[1] = address(this).balance / 1e18;
outherFactor[2] = lastTimestamp;
outherFactor[3] = participants.length;
uint winIndex;
uint count = 0;
while (count < 4) {
_structHash = keccak256(
abi.encode(
_blockhash,
outherFactor[count],
gasleft,
_externalRandomNumbers[count]
)
);
randomNumber = uint256(_structHash);
winIndex = uint256(randomNumber % length);
if (!alreadyWon(winIndex)) {
winningIndexes[count] = winIndex;
count++;
}
}
console.log("============= Winners", winningIndexes[0], winningIndexes[1], winningIndexes[2]);
console.log("============= Winners Last", winningIndexes[3]);
// Rewards
// 1,2,3
for (uint i = 0; i < 3; i++) {
address winner = participants[winningIndexes[i]];
uint rewardPercent = rewardDistribution[i];
uint256 reward;
for (uint t = 0; i < _tokensInBasket.length; t++) {
reward = IERC20(_tokensInBasket[t]).balanceOf(address(this)) * rewardPercent / 10000;
payable(winner).transfer(reward);
// lottoId -> winIndex -> tokenIndex
historyBasketAmounts[issueId][i].push(reward);
}
winningAddresses[i] = winner;
}
console.log("So MANY transfers !!!");
// 4
// TODO: Add more royalty rewards.
address nftWinner = participants[winningIndexes[3]];
winnerNFT.create(nftWinner, issueId);
winningAddresses[3] = nftWinner;
historyWinners[issueId] = winningAddresses;
historyBasketTokens[issueId] = _tokensInBasket;
emit WinnersChosen(issueId, winningAddresses);
}
function alreadyWon(uint index) internal returns (bool){
for (uint i = 0; i < winningIndexes.length; i++) {
if (winningIndexes[i] == index) {
return true;
}
}
return false;
}
// used to randomize gasLeft
function getTotalParticipants(uint256 _randomNumber) public view returns (address) {
// TODO: pass _randomNumber
address temp;
if (issueId > 0) {
uint cycle = _randomNumber % 7;
for (uint i = 0; i < cycle; i++) {
temp = historyWinners[issueId][_randomNumber % 3];
}
}
}
/* GETTERS */
function getFinishBlock() external override view returns (uint256) {
return finishBlock;
}
function active() public override view returns (bool) {
return startBlock > 0;
}
/* SETTERS */
function setRewardPercents(uint place, uint percent) public override {
rewardDistribution[place] = percent;
bool isValid = validateRewards();
require(isValid, "More than 100% !");
}
function validateRewards() internal returns (bool){
uint pSum = 0;
for (uint i = 0; i < rewardDistribution.length; i++) {
pSum += rewardDistribution[i];
}
return (pSum == 10000);
}
//Deal with BNB
fallback() external payable {}
receive() external payable {
console.log("OPSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA !");
require(startBlock != 0 && finishBlock != 0, "must have started");
this.enter(msg.sender, msg.value, address(0));
}
}
|
used to randomize gasLeft TODO: pass _randomNumber
|
function getTotalParticipants(uint256 _randomNumber) public view returns (address) {
address temp;
if (issueId > 0) {
uint cycle = _randomNumber % 7;
for (uint i = 0; i < cycle; i++) {
temp = historyWinners[issueId][_randomNumber % 3];
}
}
}
| 6,361,877
|
./full_match/1/0xF9ca2b0c777E3B601459d141eC757424F00305cD/sources/CandyCrush.sol
|
Constructor method initializes the ERC20 Token. Mints tokens to contract and marketing wallet. Sets up initial liquidity pool but liquidity cannot be added in the same tx/
|
function mint(MintParams calldata params) external payable returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
constructor() ERC20("CANDY CRUSH", "CAN") {
_mint(address(this), uniswapSupply);
_mint(marketing, marketingSupply);
_mint(team, teamSupply);
fixOrdering();
pool = posMan.createAndInitializePoolIfNecessary(token0, token1, fee, sqrtPriceX96);
}
| 9,712,959
|
./full_match/1/0xA33dCbE04278706248891931537Dd56B795c3663/sources/contracts/factories/flexi/FlexiPunkTLD.sol
|
Domain getters - you can also get all Domain data by calling the auto-generated domains(domainName) method
|
function getDomainHolder(string calldata _domainName) public override view returns(address) {
return domains[strings.lower(_domainName)].holder;
}
| 16,489,225
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import '../interfaces/IERC20.sol';
import '../interfaces/IERC721.sol';
import '../interfaces/IERC721Metadata.sol';
import '../interfaces/IERC721Receiver.sol';
import '../Dependencies/Base64.sol';
/**
@title Voting Escrow
@author Curve Finance
@notice Votes have a weight depending on time, so that users are
committed to the future of (whatever they are voting for)
@dev Vote weight decays linearly over time. Lock time cannot be
more than `MAXTIME` (4 years).
# Voting escrow to have time-weighted votes
# Votes have a weight depending on time, so that users are committed
# to the future of (whatever they are voting for).
# The weight in this implementation is linear, and lock cannot be more than maxtime:
# w ^
# 1 + /
# | /
# | /
# | /
# |/
# 0 +--------+------> time
# maxtime (4 years?)
*/
contract VotedEscrow is IERC721, IERC721Metadata {
enum DepositType {
DEPOSIT_FOR_TYPE,
CREATE_LOCK_TYPE,
INCREASE_LOCK_AMOUNT,
INCREASE_UNLOCK_TIME,
MERGE_TYPE
}
event Deposit(
address indexed provider,
uint tokenId,
uint value,
uint indexed locktime,
DepositType deposit_type,
uint ts
);
event Withdraw(address indexed provider, uint tokenId, uint value, uint ts);
event Supply(uint prevSupply, uint supply);
uint internal constant WEEK = 1 weeks;
uint internal constant MAXTIME = 4 * 365 * 86400;
int128 internal constant iMAXTIME = 4 * 365 * 86400;
uint internal constant MULTIPLIER = 1 ether;
struct Point {
int128 bias;
int128 slope; // # -dweight / dt
uint ts;
uint blk; // block
}
/* We cannot really do block numbers per se b/c slope is per time, not per block
* and per block could be fairly bad b/c Ethereum changes blocktimes.
* What we can do is to extrapolate ***At functions */
struct LockedBalance {
int128 amount;
uint end;
}
address immutable public token;
uint public supply;
uint public epoch;
mapping(uint => LockedBalance) public locked;
mapping(uint => uint) public ownership_change;
mapping(uint => Point) public point_history; // epoch -> unsigned point
mapping(uint => Point[1000000000]) public user_point_history; // user -> Point[user_epoch]
mapping(uint => uint) public user_point_epoch;
mapping(uint => int128) public slope_changes; // time -> signed slope change
mapping(uint => uint) public attachments;
mapping(uint => bool) public voted;
address public voter;
string constant public override name = "veNFT";
string constant public override symbol = "veNFT";
string constant public version = "1.0.0";
uint8 constant public decimals = 18;
/// @dev Current count of token
uint internal tokenId;
/// @dev Mapping from NFT ID to the address that owns it.
mapping(uint => address) internal idToOwner;
/// @dev Mapping from NFT ID to approved address.
mapping(uint => address) internal idToApprovals;
/// @dev Mapping from owner address to count of his tokens.
mapping(address => uint) internal ownerToNFTokenCount;
/// @dev Mapping from owner address to mapping of index to tokenIds
mapping(address => mapping(uint => uint)) internal ownerToNFTokenIdList;
/// @dev Mapping from NFT ID to index of owner
mapping(uint => uint) internal tokenToOwnerIndex;
/// @dev Mapping from owner address to mapping of operator addresses.
mapping(address => mapping(address => bool)) internal ownerToOperators;
/// @dev Mapping of interface id to bool about whether or not it's supported
mapping(bytes4 => bool) internal supportedInterfaces;
/// @dev ERC165 interface ID of ERC165
bytes4 internal constant ERC165_INTERFACE_ID = 0x01ffc9a7;
/// @dev ERC165 interface ID of ERC721
bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd;
/// @dev ERC165 interface ID of ERC721Metadata
bytes4 internal constant ERC721_METADATA_INTERFACE_ID = 0x5b5e139f;
/// @dev reentrancy guard
uint8 internal constant _not_entered = 1;
uint8 internal constant _entered = 2;
uint8 internal _entered_state = 1;
modifier nonreentrant() {
require(_entered_state == _not_entered);
_entered_state = _entered;
_;
_entered_state = _not_entered;
}
/// @notice Contract constructor
/// @param token_addr `ERC20CRV` token address
constructor(
address token_addr
) {
token = token_addr;
voter = msg.sender;
point_history[0].blk = block.number;
point_history[0].ts = block.timestamp;
supportedInterfaces[ERC165_INTERFACE_ID] = true;
supportedInterfaces[ERC721_INTERFACE_ID] = true;
supportedInterfaces[ERC721_METADATA_INTERFACE_ID] = true;
// mint-ish
emit Transfer(address(0), address(this), tokenId);
// burn-ish
emit Transfer(address(this), address(0), tokenId);
}
/// @dev Interface identification is specified in ERC-165.
/// @param _interfaceID Id of the interface
function supportsInterface(bytes4 _interfaceID) override external view returns (bool) {
return supportedInterfaces[_interfaceID];
}
/// @notice Get the most recently recorded rate of voting power decrease for `_tokenId`
/// @param _tokenId token of the NFT
/// @return Value of the slope
function get_last_user_slope(uint _tokenId) external view returns (int128) {
uint uepoch = user_point_epoch[_tokenId];
return user_point_history[_tokenId][uepoch].slope;
}
/// @notice Get the timestamp for checkpoint `_idx` for `_tokenId`
/// @param _tokenId token of the NFT
/// @param _idx User epoch number
/// @return Epoch time of the checkpoint
function user_point_history__ts(uint _tokenId, uint _idx) external view returns (uint) {
return user_point_history[_tokenId][_idx].ts;
}
/// @notice Get timestamp when `_tokenId`'s lock finishes
/// @param _tokenId User NFT
/// @return Epoch time of the lock end
function locked__end(uint _tokenId) external view returns (uint) {
return locked[_tokenId].end;
}
/// @dev Returns the number of NFTs owned by `_owner`.
/// Throws if `_owner` is the zero address. NFTs assigned to the zero address are considered invalid.
/// @param _owner Address for whom to query the balance.
function _balance(address _owner) internal view returns (uint) {
return ownerToNFTokenCount[_owner];
}
/// @dev Returns the number of NFTs owned by `_owner`.
/// Throws if `_owner` is the zero address. NFTs assigned to the zero address are considered invalid.
/// @param _owner Address for whom to query the balance.
function balanceOf(address _owner) override external view returns (uint) {
return _balance(_owner);
}
/// @dev Returns the address of the owner of the NFT.
/// @param _tokenId The identifier for an NFT.
function ownerOf(uint _tokenId) public override view returns (address) {
return idToOwner[_tokenId];
}
/// @dev Get the approved address for a single NFT.
/// @param _tokenId ID of the NFT to query the approval of.
function getApproved(uint _tokenId) external override view returns (address) {
return idToApprovals[_tokenId];
}
/// @dev Checks if `_operator` is an approved operator for `_owner`.
/// @param _owner The address that owns the NFTs.
/// @param _operator The address that acts on behalf of the owner.
function isApprovedForAll(address _owner, address _operator) override external view returns (bool) {
return (ownerToOperators[_owner])[_operator];
}
/// @dev Get token by index
function tokenOfOwnerByIndex(address _owner, uint _tokenIndex) external view returns (uint) {
return ownerToNFTokenIdList[_owner][_tokenIndex];
}
/// @dev Returns whether the given spender can transfer a given token ID
/// @param _spender address of the spender to query
/// @param _tokenId uint ID of the token to be transferred
/// @return bool whether the msg.sender is approved for the given token ID, is an operator of the owner, or is the owner of the token
function _isApprovedOrOwner(address _spender, uint _tokenId) internal view returns (bool) {
address owner = idToOwner[_tokenId];
bool spenderIsOwner = owner == _spender;
bool spenderIsApproved = _spender == idToApprovals[_tokenId];
bool spenderIsApprovedForAll = (ownerToOperators[owner])[_spender];
return spenderIsOwner || spenderIsApproved || spenderIsApprovedForAll;
}
function isApprovedOrOwner(address _spender, uint _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Add a NFT to an index mapping to a given address
/// @param _to address of the receiver
/// @param _tokenId uint ID Of the token to be added
function _addTokenToOwnerList(address _to, uint _tokenId) internal {
uint current_count = _balance(_to);
ownerToNFTokenIdList[_to][current_count] = _tokenId;
tokenToOwnerIndex[_tokenId] = current_count;
}
/// @dev Remove a NFT from an index mapping to a given address
/// @param _from address of the sender
/// @param _tokenId uint ID Of the token to be removed
function _removeTokenFromOwnerList(address _from, uint _tokenId) internal {
// Delete
uint current_count = _balance(_from)-1;
uint current_index = tokenToOwnerIndex[_tokenId];
if (current_count == current_index) {
// update ownerToNFTokenIdList
ownerToNFTokenIdList[_from][current_count] = 0;
// update tokenToOwnerIndex
tokenToOwnerIndex[_tokenId] = 0;
} else {
uint lastTokenId = ownerToNFTokenIdList[_from][current_count];
// Add
// update ownerToNFTokenIdList
ownerToNFTokenIdList[_from][current_index] = lastTokenId;
// update tokenToOwnerIndex
tokenToOwnerIndex[lastTokenId] = current_index;
// Delete
// update ownerToNFTokenIdList
ownerToNFTokenIdList[_from][current_count] = 0;
// update tokenToOwnerIndex
tokenToOwnerIndex[_tokenId] = 0;
}
}
/// @dev Add a NFT to a given address
/// Throws if `_tokenId` is owned by someone.
function _addTokenTo(address _to, uint _tokenId) internal {
// Throws if `_tokenId` is owned by someone
assert(idToOwner[_tokenId] == address(0));
// Change the owner
idToOwner[_tokenId] = _to;
// Update owner token index tracking
_addTokenToOwnerList(_to, _tokenId);
// Change count tracking
ownerToNFTokenCount[_to] += 1;
}
/// @dev Remove a NFT from a given address
/// Throws if `_from` is not the current owner.
function _removeTokenFrom(address _from, uint _tokenId) internal {
// Throws if `_from` is not the current owner
assert(idToOwner[_tokenId] == _from);
// Change the owner
idToOwner[_tokenId] = address(0);
// Update owner token index tracking
_removeTokenFromOwnerList(_from, _tokenId);
// Change count tracking
ownerToNFTokenCount[_from] -= 1;
}
/// @dev Clear an approval of a given address
/// Throws if `_owner` is not the current owner.
function _clearApproval(address _owner, uint _tokenId) internal {
// Throws if `_owner` is not the current owner
assert(idToOwner[_tokenId] == _owner);
if (idToApprovals[_tokenId] != address(0)) {
// Reset approvals
idToApprovals[_tokenId] = address(0);
}
}
/// @dev Exeute transfer of a NFT.
/// Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
/// address for this NFT. (NOTE: `msg.sender` not allowed in internal function so pass `_sender`.)
/// Throws if `_to` is the zero address.
/// Throws if `_from` is not the current owner.
/// Throws if `_tokenId` is not a valid NFT.
function _transferFrom(
address _from,
address _to,
uint _tokenId,
address _sender
) internal {
require(attachments[_tokenId] == 0 && !voted[_tokenId], "attached");
// Check requirements
require(_isApprovedOrOwner(_sender, _tokenId));
// Clear approval. Throws if `_from` is not the current owner
_clearApproval(_from, _tokenId);
// Remove NFT. Throws if `_tokenId` is not a valid NFT
_removeTokenFrom(_from, _tokenId);
// Add NFT
_addTokenTo(_to, _tokenId);
// Set the block of ownership transfer (for Flash NFT protection)
ownership_change[_tokenId] = block.number;
// Log the transfer
emit Transfer(_from, _to, _tokenId);
}
/* TRANSFER FUNCTIONS */
/// @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.
/// @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
/// they maybe be permanently lost.
/// @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,
uint _tokenId
) external override {
_transferFrom(_from, _to, _tokenId, msg.sender);
}
function _isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/// @dev Transfers the ownership of an NFT from one address to another address.
/// 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.
/// If `_to` is a smart contract, it calls `onERC721Received` on `_to` and throws if
/// the return value is not `bytes4(keccak256("onERC721Received(address,address,uint,bytes)"))`.
/// @param _from The current owner of the NFT.
/// @param _to The new owner.
/// @param _tokenId The NFT to transfer.
/// @param _data Additional data with no specified format, sent in call to `_to`.
function safeTransferFrom(
address _from,
address _to,
uint _tokenId,
bytes memory _data
) public override {
_transferFrom(_from, _to, _tokenId, msg.sender);
if (_isContract(_to)) {
// Throws if transfer destination is a contract which does not implement 'onERC721Received'
try IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) returns (bytes4) {} catch (
bytes memory reason
) {
if (reason.length == 0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/// @dev Transfers the ownership of an NFT from one address to another address.
/// 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.
/// If `_to` is a smart contract, it calls `onERC721Received` on `_to` and throws if
/// the return value is not `bytes4(keccak256("onERC721Received(address,address,uint,bytes)"))`.
/// @param _from The current owner of the NFT.
/// @param _to The new owner.
/// @param _tokenId The NFT to transfer.
function safeTransferFrom(
address _from,
address _to,
uint _tokenId
) external override {
safeTransferFrom(_from, _to, _tokenId, '');
}
/// @dev Set or reaffirm the approved address for an NFT. The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized operator of the current owner.
/// Throws if `_tokenId` is not a valid NFT. (NOTE: This is not written the EIP)
/// Throws if `_approved` is the current owner. (NOTE: This is not written the EIP)
/// @param _approved Address to be approved for the given NFT ID.
/// @param _tokenId ID of the token to be approved.
function approve(address _approved, uint _tokenId) override public {
address owner = idToOwner[_tokenId];
// Throws if `_tokenId` is not a valid NFT
require(owner != address(0));
// Throws if `_approved` is the current owner
require(_approved != owner);
// Check requirements
bool senderIsOwner = (idToOwner[_tokenId] == msg.sender);
bool senderIsApprovedForAll = (ownerToOperators[owner])[msg.sender];
require(senderIsOwner || senderIsApprovedForAll);
// Set the approval
idToApprovals[_tokenId] = _approved;
emit Approval(owner, _approved, _tokenId);
}
/// @dev Enables or disables approval for a third party ("operator") to manage all of
/// `msg.sender`'s assets. It also emits the ApprovalForAll event.
/// Throws if `_operator` is the `msg.sender`. (NOTE: This is not written the EIP)
/// @notice This works even if sender doesn't own any tokens at the time.
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval.
function setApprovalForAll(address _operator, bool _approved) external override {
// Throws if `_operator` is the `msg.sender`
assert(_operator != msg.sender);
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @dev Function to mint tokens
/// Throws if `_to` is zero address.
/// Throws if `_tokenId` is owned by someone.
/// @param _to The address that will receive the minted tokens.
/// @param _tokenId The token id to mint.
/// @return A boolean that indicates if the operation was successful.
function _mint(address _to, uint _tokenId) internal returns (bool) {
// Throws if `_to` is zero address
assert(_to != address(0));
// Add NFT. Throws if `_tokenId` is owned by someone
_addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
return true;
}
/// @notice Record global and per-user data to checkpoint
/// @param _tokenId NFT token ID. No user checkpoint if 0
/// @param old_locked Pevious locked amount / end lock time for the user
/// @param new_locked New locked amount / end lock time for the user
function _checkpoint(
uint _tokenId,
LockedBalance memory old_locked,
LockedBalance memory new_locked
) internal {
Point memory u_old;
Point memory u_new;
int128 old_dslope = 0;
int128 new_dslope = 0;
uint _epoch = epoch;
if (_tokenId != 0) {
// Calculate slopes and biases
// Kept at zero when they have to
if (old_locked.end > block.timestamp && old_locked.amount > 0) {
u_old.slope = old_locked.amount / iMAXTIME;
u_old.bias = u_old.slope * int128(int256(old_locked.end - block.timestamp));
}
if (new_locked.end > block.timestamp && new_locked.amount > 0) {
u_new.slope = new_locked.amount / iMAXTIME;
u_new.bias = u_new.slope * int128(int256(new_locked.end - block.timestamp));
}
// Read values of scheduled changes in the slope
// old_locked.end can be in the past and in the future
// new_locked.end can ONLY by in the FUTURE unless everything expired: than zeros
old_dslope = slope_changes[old_locked.end];
if (new_locked.end != 0) {
if (new_locked.end == old_locked.end) {
new_dslope = old_dslope;
} else {
new_dslope = slope_changes[new_locked.end];
}
}
}
Point memory last_point = Point({bias: 0, slope: 0, ts: block.timestamp, blk: block.number});
if (_epoch > 0) {
last_point = point_history[_epoch];
}
uint last_checkpoint = last_point.ts;
// initial_last_point is used for extrapolation to calculate block number
// (approximately, for *At methods) and save them
// as we cannot figure that out exactly from inside the contract
Point memory initial_last_point = last_point;
uint block_slope = 0; // dblock/dt
if (block.timestamp > last_point.ts) {
block_slope = (MULTIPLIER * (block.number - last_point.blk)) / (block.timestamp - last_point.ts);
}
// If last point is already recorded in this block, slope=0
// But that's ok b/c we know the block in such case
// Go over weeks to fill history and calculate what the current point is
{
uint t_i = (last_checkpoint / WEEK) * WEEK;
for (uint i = 0; i < 255; ++i) {
// Hopefully it won't happen that this won't get used in 5 years!
// If it does, users will be able to withdraw but vote weight will be broken
t_i += WEEK;
int128 d_slope = 0;
if (t_i > block.timestamp) {
t_i = block.timestamp;
} else {
d_slope = slope_changes[t_i];
}
last_point.bias -= last_point.slope * int128(int256(t_i - last_checkpoint));
last_point.slope += d_slope;
if (last_point.bias < 0) {
// This can happen
last_point.bias = 0;
}
if (last_point.slope < 0) {
// This cannot happen - just in case
last_point.slope = 0;
}
last_checkpoint = t_i;
last_point.ts = t_i;
last_point.blk = initial_last_point.blk + (block_slope * (t_i - initial_last_point.ts)) / MULTIPLIER;
_epoch += 1;
if (t_i == block.timestamp) {
last_point.blk = block.number;
break;
} else {
point_history[_epoch] = last_point;
}
}
}
epoch = _epoch;
// Now point_history is filled until t=now
if (_tokenId != 0) {
// If last point was in this block, the slope change has been applied already
// But in such case we have 0 slope(s)
last_point.slope += (u_new.slope - u_old.slope);
last_point.bias += (u_new.bias - u_old.bias);
if (last_point.slope < 0) {
last_point.slope = 0;
}
if (last_point.bias < 0) {
last_point.bias = 0;
}
}
// Record the changed point into history
point_history[_epoch] = last_point;
if (_tokenId != 0) {
// Schedule the slope changes (slope is going down)
// We subtract new_user_slope from [new_locked.end]
// and add old_user_slope to [old_locked.end]
if (old_locked.end > block.timestamp) {
// old_dslope was <something> - u_old.slope, so we cancel that
old_dslope += u_old.slope;
if (new_locked.end == old_locked.end) {
old_dslope -= u_new.slope; // It was a new deposit, not extension
}
slope_changes[old_locked.end] = old_dslope;
}
if (new_locked.end > block.timestamp) {
if (new_locked.end > old_locked.end) {
new_dslope -= u_new.slope; // old slope disappeared at this point
slope_changes[new_locked.end] = new_dslope;
}
// else: we recorded it already in old_dslope
}
// Now handle user history
uint user_epoch = user_point_epoch[_tokenId] + 1;
user_point_epoch[_tokenId] = user_epoch;
u_new.ts = block.timestamp;
u_new.blk = block.number;
user_point_history[_tokenId][user_epoch] = u_new;
}
}
/// @notice Deposit and lock tokens for a user
/// @param _tokenId NFT that holds lock
/// @param _value Amount to deposit
/// @param unlock_time New time when to unlock the tokens, or 0 if unchanged
/// @param locked_balance Previous locked amount / timestamp
/// @param deposit_type The type of deposit
function _deposit_for(
uint _tokenId,
uint _value,
uint unlock_time,
LockedBalance memory locked_balance,
DepositType deposit_type
) internal {
LockedBalance memory _locked = locked_balance;
uint supply_before = supply;
supply = supply_before + _value;
LockedBalance memory old_locked;
(old_locked.amount, old_locked.end) = (_locked.amount, _locked.end);
// Adding to existing lock, or if a lock is expired - creating a new one
_locked.amount += int128(int256(_value));
if (unlock_time != 0) {
_locked.end = unlock_time;
}
locked[_tokenId] = _locked;
// Possibilities:
// Both old_locked.end could be current or expired (>/< block.timestamp)
// value == 0 (extend lock) or value > 0 (add to lock or extend lock)
// _locked.end > block.timestamp (always)
_checkpoint(_tokenId, old_locked, _locked);
address from = msg.sender;
if (_value != 0 && deposit_type != DepositType.MERGE_TYPE) {
assert(IERC20(token).transferFrom(from, address(this), _value));
}
emit Deposit(from, _tokenId, _value, _locked.end, deposit_type, block.timestamp);
emit Supply(supply_before, supply_before + _value);
}
function setVoter(address _voter) external {
require(msg.sender == voter);
voter = _voter;
}
function voting(uint _tokenId) external {
require(msg.sender == voter);
voted[_tokenId] = true;
}
function abstain(uint _tokenId) external {
require(msg.sender == voter);
voted[_tokenId] = false;
}
function attach(uint _tokenId) external {
require(msg.sender == voter);
attachments[_tokenId] = attachments[_tokenId]+1;
}
function detach(uint _tokenId) external {
require(msg.sender == voter);
attachments[_tokenId] = attachments[_tokenId]-1;
}
function merge(uint _from, uint _to) external {
require(attachments[_from] == 0 && !voted[_from], "attached");
require(_from != _to);
require(_isApprovedOrOwner(msg.sender, _from));
require(_isApprovedOrOwner(msg.sender, _to));
LockedBalance memory _locked0 = locked[_from];
LockedBalance memory _locked1 = locked[_to];
uint value0 = uint(int256(_locked0.amount));
uint end = _locked0.end >= _locked1.end ? _locked0.end : _locked1.end;
locked[_from] = LockedBalance(0, 0);
_checkpoint(_from, _locked0, LockedBalance(0, 0));
_burn(_from);
_deposit_for(_to, value0, end, _locked1, DepositType.MERGE_TYPE);
}
function block_number() external view returns (uint) {
return block.number;
}
/// @notice Record global data to checkpoint
function checkpoint() external {
_checkpoint(0, LockedBalance(0, 0), LockedBalance(0, 0));
}
/// @notice Deposit `_value` tokens for `_tokenId` and add to the lock
/// @dev Anyone (even a smart contract) can deposit for someone else, but
/// cannot extend their locktime and deposit for a brand new user
/// @param _tokenId lock NFT
/// @param _value Amount to add to user's lock
function deposit_for(uint _tokenId, uint _value) external nonreentrant {
LockedBalance memory _locked = locked[_tokenId];
require(_value > 0); // dev: need non-zero value
require(_locked.amount > 0, 'No existing lock found');
require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw');
_deposit_for(_tokenId, _value, 0, _locked, DepositType.DEPOSIT_FOR_TYPE);
}
/// @notice Deposit `_value` tokens for `_to` and lock for `_lock_duration`
/// @param _value Amount to deposit
/// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week)
/// @param _to Address to deposit
function _create_lock(uint _value, uint _lock_duration, address _to) internal returns (uint) {
uint unlock_time = (block.timestamp + _lock_duration) / WEEK * WEEK; // Locktime is rounded down to weeks
require(_value > 0); // dev: need non-zero value
require(unlock_time > block.timestamp, 'Can only lock until time in the future');
require(unlock_time <= block.timestamp + MAXTIME, 'Voting lock can be 4 years max');
++tokenId;
uint _tokenId = tokenId;
_mint(_to, _tokenId);
_deposit_for(_tokenId, _value, unlock_time, locked[_tokenId], DepositType.CREATE_LOCK_TYPE);
return _tokenId;
}
/// @notice Deposit `_value` tokens for `_to` and lock for `_lock_duration`
/// @param _value Amount to deposit
/// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week)
/// @param _to Address to deposit
function create_lock_for(uint _value, uint _lock_duration, address _to) external nonreentrant returns (uint) {
return _create_lock(_value, _lock_duration, _to);
}
/// @notice Deposit `_value` tokens for `msg.sender` and lock for `_lock_duration`
/// @param _value Amount to deposit
/// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week)
function create_lock(uint _value, uint _lock_duration) external nonreentrant returns (uint) {
return _create_lock(_value, _lock_duration, msg.sender);
}
/// @notice Deposit `_value` additional tokens for `_tokenId` without modifying the unlock time
/// @param _value Amount of tokens to deposit and add to the lock
function increase_amount(uint _tokenId, uint _value) external nonreentrant {
assert(_isApprovedOrOwner(msg.sender, _tokenId));
LockedBalance memory _locked = locked[_tokenId];
assert(_value > 0); // dev: need non-zero value
require(_locked.amount > 0, 'No existing lock found');
require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw');
_deposit_for(_tokenId, _value, 0, _locked, DepositType.INCREASE_LOCK_AMOUNT);
}
/// @notice Extend the unlock time for `_tokenId`
/// @param _lock_duration New number of seconds until tokens unlock
function increase_unlock_time(uint _tokenId, uint _lock_duration) external nonreentrant {
assert(_isApprovedOrOwner(msg.sender, _tokenId));
LockedBalance memory _locked = locked[_tokenId];
uint unlock_time = (block.timestamp + _lock_duration) / WEEK * WEEK; // Locktime is rounded down to weeks
require(_locked.end > block.timestamp, 'Lock expired');
require(_locked.amount > 0, 'Nothing is locked');
require(unlock_time > _locked.end, 'Can only increase lock duration');
require(unlock_time <= block.timestamp + MAXTIME, 'Voting lock can be 4 years max');
_deposit_for(_tokenId, 0, unlock_time, _locked, DepositType.INCREASE_UNLOCK_TIME);
}
/// @notice Withdraw all tokens for `_tokenId`
/// @dev Only possible if the lock has expired
function withdraw(uint _tokenId) external nonreentrant {
assert(_isApprovedOrOwner(msg.sender, _tokenId));
require(attachments[_tokenId] == 0 && !voted[_tokenId], "attached");
LockedBalance memory _locked = locked[_tokenId];
require(block.timestamp >= _locked.end, "The lock didn't expire");
uint value = uint(int256(_locked.amount));
locked[_tokenId] = LockedBalance(0,0);
uint supply_before = supply;
supply = supply_before - value;
// old_locked can have either expired <= timestamp or zero end
// _locked has only 0 end
// Both can have >= 0 amount
_checkpoint(_tokenId, _locked, LockedBalance(0,0));
assert(IERC20(token).transfer(msg.sender, value));
// Burn the NFT
_burn(_tokenId);
emit Withdraw(msg.sender, _tokenId, value, block.timestamp);
emit Supply(supply_before, supply_before - value);
}
// The following ERC20/minime-compatible methods are not real balanceOf and supply!
// They measure the weights for the purpose of voting, so they don't represent
// real coins.
/// @notice Binary search to estimate timestamp for block number
/// @param _block Block to find
/// @param max_epoch Don't go beyond this epoch
/// @return Approximate timestamp for block
function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) {
// Binary search
uint _min = 0;
uint _max = max_epoch;
for (uint i = 0; i < 128; ++i) {
// Will be always enough for 128-bit numbers
if (_min >= _max) {
break;
}
uint _mid = (_min + _max + 1) / 2;
if (point_history[_mid].blk <= _block) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
return _min;
}
/// @notice Get the current voting power for `_tokenId`
/// @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility
/// @param _tokenId NFT for lock
/// @param _t Epoch time to return voting power at
/// @return User voting power
function _balanceOfNFT(uint _tokenId, uint _t) internal view returns (uint) {
uint _epoch = user_point_epoch[_tokenId];
if (_epoch == 0) {
return 0;
} else {
Point memory last_point = user_point_history[_tokenId][_epoch];
last_point.bias -= last_point.slope * int128(int256(_t) - int256(last_point.ts));
if (last_point.bias < 0) {
last_point.bias = 0;
}
return uint(int256(last_point.bias));
}
}
/// @dev Returns current token URI metadata
/// @param _tokenId Token ID to fetch URI for.
function tokenURI(uint _tokenId) external view override returns (string memory) {
require(idToOwner[_tokenId] != address(0), "Query for nonexistent token");
LockedBalance memory _locked = locked[_tokenId];
return
_tokenURI(
_tokenId,
_balanceOfNFT(_tokenId, block.timestamp),
_locked.end,
uint(int256(_locked.amount))
);
}
function balanceOfNFT(uint _tokenId) external view returns (uint) {
if (ownership_change[_tokenId] == block.number) return 0;
return _balanceOfNFT(_tokenId, block.timestamp);
}
function balanceOfNFTAt(uint _tokenId, uint _t) external view returns (uint) {
return _balanceOfNFT(_tokenId, _t);
}
/// @notice Measure voting power of `_tokenId` at block height `_block`
/// @dev Adheres to MiniMe `balanceOfAt` interface: https://github.com/Giveth/minime
/// @param _tokenId User's wallet NFT
/// @param _block Block to calculate the voting power at
/// @return Voting power
function _balanceOfAtNFT(uint _tokenId, uint _block) internal view returns (uint) {
// Copying and pasting totalSupply code because Vyper cannot pass by
// reference yet
assert(_block <= block.number);
// Binary search
uint _min = 0;
uint _max = user_point_epoch[_tokenId];
for (uint i = 0; i < 128; ++i) {
// Will be always enough for 128-bit numbers
if (_min >= _max) {
break;
}
uint _mid = (_min + _max + 1) / 2;
if (user_point_history[_tokenId][_mid].blk <= _block) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
Point memory upoint = user_point_history[_tokenId][_min];
uint max_epoch = epoch;
uint _epoch = _find_block_epoch(_block, max_epoch);
Point memory point_0 = point_history[_epoch];
uint d_block = 0;
uint d_t = 0;
if (_epoch < max_epoch) {
Point memory point_1 = point_history[_epoch + 1];
d_block = point_1.blk - point_0.blk;
d_t = point_1.ts - point_0.ts;
} else {
d_block = block.number - point_0.blk;
d_t = block.timestamp - point_0.ts;
}
uint block_time = point_0.ts;
if (d_block != 0) {
block_time += (d_t * (_block - point_0.blk)) / d_block;
}
upoint.bias -= upoint.slope * int128(int256(block_time - upoint.ts));
if (upoint.bias >= 0) {
return uint(uint128(upoint.bias));
} else {
return 0;
}
}
function balanceOfAtNFT(uint _tokenId, uint _block) external view returns (uint) {
return _balanceOfAtNFT(_tokenId, _block);
}
/// @notice Calculate total voting power at some point in the past
/// @param point The point (bias/slope) to start search from
/// @param t Time to calculate the total voting power at
/// @return Total voting power at that time
function _supply_at(Point memory point, uint t) internal view returns (uint) {
Point memory last_point = point;
uint t_i = (last_point.ts / WEEK) * WEEK;
for (uint i = 0; i < 255; ++i) {
t_i += WEEK;
int128 d_slope = 0;
if (t_i > t) {
t_i = t;
} else {
d_slope = slope_changes[t_i];
}
last_point.bias -= last_point.slope * int128(int256(t_i - last_point.ts));
if (t_i == t) {
break;
}
last_point.slope += d_slope;
last_point.ts = t_i;
}
if (last_point.bias < 0) {
last_point.bias = 0;
}
return uint(uint128(last_point.bias));
}
/// @notice Calculate total voting power
/// @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility
/// @return Total voting power
function totalSupplyAtT(uint t) public view returns (uint) {
uint _epoch = epoch;
Point memory last_point = point_history[_epoch];
return _supply_at(last_point, t);
}
function totalSupply() external view returns (uint) {
return totalSupplyAtT(block.timestamp);
}
/// @notice Calculate total voting power at some point in the past
/// @param _block Block to calculate the total voting power at
/// @return Total voting power at `_block`
function totalSupplyAt(uint _block) external view returns (uint) {
assert(_block <= block.number);
uint _epoch = epoch;
uint target_epoch = _find_block_epoch(_block, _epoch);
Point memory point = point_history[target_epoch];
uint dt = 0;
if (target_epoch < _epoch) {
Point memory point_next = point_history[target_epoch + 1];
if (point.blk != point_next.blk) {
dt = ((_block - point.blk) * (point_next.ts - point.ts)) / (point_next.blk - point.blk);
}
} else {
if (point.blk != block.number) {
dt = ((_block - point.blk) * (block.timestamp - point.ts)) / (block.number - point.blk);
}
}
// Now dt contains info on how far are we beyond point
return _supply_at(point, point.ts + dt);
}
function _tokenURI(uint _tokenId, uint _balanceOf, uint _locked_end, uint _value) internal pure returns (string memory output) {
output = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
output = string(abi.encodePacked(output, "token ", toString(_tokenId), '</text><text x="10" y="40" class="base">'));
output = string(abi.encodePacked(output, "balanceOf ", toString(_balanceOf), '</text><text x="10" y="60" class="base">'));
output = string(abi.encodePacked(output, "locked_end ", toString(_locked_end), '</text><text x="10" y="80" class="base">'));
output = string(abi.encodePacked(output, "value ", toString(_value), '</text></svg>'));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "lock #', toString(_tokenId), '", "description": "Solidly locks, can be used to boost gauge yields, vote on token emission, and receive bribes", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
}
function toString(uint value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
function _burn(uint _tokenId) internal {
require(_isApprovedOrOwner(msg.sender, _tokenId), "caller is not owner nor approved");
address owner = ownerOf(_tokenId);
// Clear approval
approve(address(0), _tokenId);
// Remove token
_removeTokenFrom(msg.sender, _tokenId);
emit Transfer(owner, address(0), _tokenId);
}
}
|
Get the most recently recorded rate of voting power decrease for `_tokenId` _tokenId token of the NFT return Value of the slope
|
function get_last_user_slope(uint _tokenId) external view returns (int128) {
uint uepoch = user_point_epoch[_tokenId];
return user_point_history[_tokenId][uepoch].slope;
}
| 899,995
|
./full_match/43113/0x623f861B0528Eb29a47833f328077dc61c9278c1/sources/contracts/MozzaToken.sol
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MOZZA::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MOZZA::delegateBySig: invalid nonce");
require(now <= expiry, "MOZZA::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 7,179,276
|
pragma solidity ^0.6.0;
import "./Reputation.sol";
import "./Finalizer.sol";
/**
* @title Arena contract handles the main logic for decimal odds betting
*/
contract Arena is Finalizer, Reputation{
uint256 public uuid;
address owner;
struct Match {
address admin;
uint256 teamA;
uint256 teamB;
uint256 winner;
uint256 totalPayoutA;
uint256 totalPayoutB;
uint256 bookieMargin;
uint256 totalCollection;
uint256 bookiePayout;
uint256 oddsA; //Granularity - 100
uint256 oddsB;
string apiUrl; //API url to retrieve the winner of the match
bool ended;
uint256[] oddsHistoryA;
uint256[] oddsHistoryB;
mapping(address => mapping(uint256 => uint256)) betA;
mapping(address => mapping(uint256 => uint256)) betB;
}
mapping(uint256 => Match) public idToMatch;
constructor() public Finalizer() {
uuid = 1;
owner = msg.sender;
}
/**
* @notice createMatch enables the setting up of a new betting book for a match.
* @param _teamA id of first team
* @param _teamB id of second team
* @param _oddsA initial odds for team A
* @param _oddsB initial odds for team B
* @param _url result url
*/
function createMatch(
uint256 _teamA,
uint256 _teamB,
uint256 _oddsA,
uint256 _oddsB,
string memory _url
) public payable validOdds(_oddsA, _oddsB) {
Match memory newMatch = Match(
msg.sender,
_teamA,
_teamB,
0,
0,
0,
msg.value,
0,
0,
_oddsA,
_oddsB,
_url,
false,
new uint256[](0),
new uint256[](0)
);
idToMatch[uuid] = newMatch;
idToMatch[uuid].oddsHistoryA.push(_oddsA);
idToMatch[uuid].oddsHistoryB.push(_oddsB);
uuid++;
}
/**
* @notice allows placing of bets
* @param _matchId the id of the match
* @param _team The team being selected
*/
function bet(uint256 _matchId, uint256 _team) public payable validBet(_matchId) {
Match storage _match = idToMatch[_matchId];
if(_team == 0) {
_match.betA[msg.sender][_match.oddsA] += msg.value;
_match.totalPayoutA += (msg.value * _match.oddsA) / 100;
} else if(_team == 1) {
_match.betB[msg.sender][_match.oddsB] += msg.value;
_match.totalPayoutB += (msg.value * _match.oddsB) / 100;
}
_match.totalCollection += msg.value;
}
/**
* @notice allows the admin to change the odds
*/
function changeOdds(uint256 _matchId, uint256 _oddsA, uint256 _oddsB)
public onlyAdmin(_matchId) validOdds(_oddsA, _oddsB){
Match storage _match = idToMatch[_matchId];
require(!_match.ended, "match has ended");
if(_oddsA != _match.oddsA) {
_match.oddsA = _oddsA;
_match.oddsHistoryA.push(_oddsA);
}
if(_oddsB != _match.oddsB) {
_match.oddsB = _oddsB;
_match.oddsHistoryB.push(_oddsB);
}
}
/**
* @notice allows the admin to add to the margin of a bet
*/
function addMargin(uint256 _matchId) public payable onlyAdmin(_matchId) {
Match storage _match = idToMatch[_matchId];
require(!_match.ended, "not allowed");
require(msg.value > 0, "invalid amount");
_match.bookieMargin += msg.value;
}
/**
* @notice allows the admin to close a match that is over
*/
function closeMatch(uint256 _matchId) public onlyAdmin(_matchId) {
Match storage _match = idToMatch[_matchId];
require(!_match.ended, "match has already ended");
requestResult(_match.apiUrl, _matchId, this.setResult.selector);
}
/**
* @notice called by the oracle to set the result
*/
function setResult(bytes32 _requestId, uint256 _result) public recordChainlinkFulfillment(_requestId){
uint256 _id = requestIdToMatch[_requestId];
Match storage _match = idToMatch[_id];
_match.ended = true;
_match.winner = _result;
if(_result == _match.teamA){
require((_match.totalCollection + _match.bookieMargin) >= _match.totalPayoutA,
"insufficient payout amount");
_match.bookiePayout = (_match.totalCollection + _match.bookieMargin) - _match.totalPayoutA;
} else if(_result == _match.teamB) {
require((_match.totalCollection + _match.bookieMargin) >= _match.totalPayoutB,
"insufficient payout amount");
_match.bookiePayout = (_match.totalCollection + _match.bookieMargin) - _match.totalPayoutB;
}
increaseRep(_match.admin);
}
/**
* @notice allows the bettor to retrieve payout if they have won.
*/
function retrievePayout(uint256 _matchId, uint256 _odds) public {
Match storage _match = idToMatch[_matchId];
require(_match.ended, "match has not been closed");
if(_match.winner != 0) {
if(_match.winner == _match.teamA) {
require(_match.betA[msg.sender][_odds] > 0, "no payout for this odds");
uint256 _amt = (_match.betA[msg.sender][_odds] * _odds) / 100;
_match.betA[msg.sender][_odds] = 0;
(bool success, ) = msg.sender.call.value(_amt)("");
require(success, "transfer failed");
} else {
require(_match.betB[msg.sender][_odds] > 0, "no payout for this odds");
uint256 _amt = (_match.betB[msg.sender][_odds] * _odds) / 100;
_match.betB[msg.sender][_odds] = 0;
(bool success, ) = msg.sender.call.value(_amt)("");
require(success, "transfer failed");
}
} else {
if(_match.betA[msg.sender][_odds] > 0) {
uint256 _amt = _match.betA[msg.sender][_odds];
_match.betA[msg.sender][_odds] = 0;
(bool success, ) = msg.sender.call.value(_amt)("");
require(success, "transfer failed");
}
if(_match.betB[msg.sender][_odds] > 0) {
uint256 _amt = _match.betB[msg.sender][_odds];
_match.betB[msg.sender][_odds] = 0;
(bool success, ) = msg.sender.call.value(_amt)("");
require(success, "transfer failed");
}
}
}
/**
* @notice allows the owner of the dapp to margin call a bookie
*/
function marginCall(uint256 _matchId) public {
require(msg.sender == owner, "not authorized");
Match storage _match = idToMatch[_matchId];
require(!_match.ended, "match has ended");
require((_match.totalCollection + _match.bookieMargin) < _match.totalPayoutA ||
(_match.totalCollection + _match.bookieMargin) < _match.totalPayoutB,
"margin satisfied");
_match.ended = true;
(bool success1, ) = msg.sender.call.value(_match.bookieMargin / 5)("");
require(success1, "transaction failed");
(bool success2, ) = _match.admin.call.value((_match.bookieMargin * 4) / 5)("");
require(success2, "transaction failed");
decreaseRep(_match.admin);
}
/**
* @notice allows the admin of a match to retrieve the payout
*/
function retrieveBookiePayout(uint256 _matchId) onlyAdmin(_matchId) public {
Match storage _match = idToMatch[_matchId];
require(_match.ended, "match is yet to end");
require(_match.bookiePayout > 0, "no payout");
uint256 _amt = _match.bookiePayout;
_match.bookiePayout = 0;
(bool success, ) = msg.sender.call.value(_amt)("");
require(success, "transaction failed");
}
/**
* @notice utility to help get the odds history
*/
function getOddsHistory(uint256 _matchId) public view returns(uint256[] memory, uint256[] memory) {
Match storage _match = idToMatch[_matchId];
return(_match.oddsHistoryA, _match.oddsHistoryB);
}
/**
* @notice utility to get the bet for a specific odds
*/
function getBetA(uint256 _matchId, uint256 _odds) public view returns(uint256) {
Match storage _match = idToMatch[_matchId];
return _match.betA[msg.sender][_odds];
}
/**
* @notice utility to get the bet for a specific odds
*/
function getBetB(uint256 _matchId, uint256 _odds) public view returns(uint256) {
Match storage _match = idToMatch[_matchId];
return _match.betB[msg.sender][_odds];
}
modifier onlyAdmin(uint256 _id) {
Match storage _match = idToMatch[_id];
require(msg.sender == _match.admin, "not authorized");
_;
}
modifier validBet(uint256 _id) {
Match storage _match = idToMatch[_id];
require(!_match.ended, "match has already ended.");
require(msg.value > 0, "invalid bet amount");
_;
}
modifier validOdds(uint256 _oddsA, uint256 _oddsB) {
require(_oddsA >= 1, "invalid odds for team A");
require(_oddsB >= 1, "invalid odds for team B");
_;
}
}
|
createMatch enables the setting up of a new betting book for a match. _teamA id of first team _teamB id of second team _oddsA initial odds for team A _oddsB initial odds for team B _url result url/
|
function createMatch(
uint256 _teamA,
uint256 _teamB,
uint256 _oddsA,
uint256 _oddsB,
string memory _url
) public payable validOdds(_oddsA, _oddsB) {
Match memory newMatch = Match(
msg.sender,
_teamA,
_teamB,
0,
0,
0,
msg.value,
0,
0,
_oddsA,
_oddsB,
_url,
false,
new uint256[](0),
new uint256[](0)
);
idToMatch[uuid] = newMatch;
idToMatch[uuid].oddsHistoryA.push(_oddsA);
idToMatch[uuid].oddsHistoryB.push(_oddsB);
uuid++;
}
| 5,528,032
|
/**
*Submitted for verification at Etherscan.io on 2020-11-12
*/
pragma solidity ^0.5.16;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) {
// 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;
}
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;
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require( address(this).balance >= amount, "Address: insufficient balance" );
(bool success, ) = recipient.call.value(amount)("");
require( success, "Address: unable to send value, recipient may have reverted" );
}
}
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 mint(address account, uint256 amount) external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval( address indexed owner, address indexed spender, uint256 value );
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); }
function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal {
callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) );
}
function safeApprove( IERC20 token, address spender, uint256 value ) internal {
require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" );
callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) );
}
function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal {
uint256 newAllowance = token.allowance(address(this), spender).add( value );
callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) );
}
function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" );
callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) );
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" );
}
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor( string memory name, string memory symbol, uint8 decimals ) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function symbol() public view returns (string memory) {
return _symbol; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function decimals() public view returns (uint8) {
return _decimals; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
/**
* Vault Strategy Interface
*/
interface IGOFStrategy {
function want() external view returns (address);
function deposit() external;
function withdraw(address) external;
function withdraw(uint) external;
function withdrawAll() external returns (uint);
function balanceOf() external view returns (uint);
}
/**
*
*/
interface Converter {
function convert(address) external returns (uint);
}
/**
*
*/
interface OneSplitAudit {
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
)
external
payable
returns(uint256 returnAmount);
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
/**
* @dev
* The controller of Strategy
* Distribute different strategies according to different tokens
*/
contract GOFStrategyControllerV2 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address internal governance;
address internal strategist;
address internal onesplit;
address internal rewards;
address internal factory;
mapping(address => address) internal vaults;
mapping(address => address) internal strategies;
mapping(address => mapping(address => address)) internal converters;
mapping(address => mapping(address => bool)) internal approvedStrategies;
uint internal split = 500;
uint internal constant max = 10000;
constructor(address _rewards) public {
governance = tx.origin;
strategist = tx.origin;
onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
rewards = _rewards;
}
function setFactory(address _factory) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
factory = _factory; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setSplit(uint _split) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
split = _split; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setOneSplit(address _onesplit) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
onesplit = _onesplit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
governance = _governance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setRewards(address _rewards) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
rewards = _rewards; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setVault(address _token, address _vault) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!strategist"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(vaults[_token] == address(0), "Golff:vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
vaults[_token] = _vault; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function approveStrategy(address _token, address _strategy) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
approvedStrategies[_token][_strategy] = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function revokeStrategy(address _token, address _strategy) public {
require(msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
approvedStrategies[_token][_strategy] = false; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setConverter(address _input, address _output, address _converter) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!strategist"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
converters[_input][_output] = _converter; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setStrategy(address _token, address _strategy) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!strategist"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(approvedStrategies[_token][_strategy] == true, "Golff:!approved"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address _current = strategies[_token]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//111111,111111111111
if (_current != address(0)) {
IGOFStrategy(_current).withdrawAll();
}
strategies[_token] = _strategy; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* 1111
* @param _token staking token
* @param _amount staking amount
*/
function earn(address _token, uint _amount) public {
address _strategy = strategies[_token]; //111111111 //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address _want = IGOFStrategy(_strategy).want();//11111token11
if (_want != _token) {//11111111111111,11111
address converter = converters[_token][_want];//1111111. //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
IERC20(_token).safeTransfer(converter, _amount);//111111
_amount = Converter(converter).convert(_strategy);//1111...
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
IGOFStrategy(_strategy).deposit();//11
}
/**
* 11token111
* @param _token staking token
*/
function balanceOf(address _token) external view returns (uint) {
return IGOFStrategy(strategies[_token]).balanceOf(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* 1111
* @param _token staking token
*/
function withdrawAll(address _token) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
IGOFStrategy(strategies[_token]).withdrawAll(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
*
*/
function inCaseTokensGetStuck(address _token, uint _amount) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
IERC20(_token).safeTransfer(governance, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
*
*/
function getExpectedReturn(address _strategy, address _token, uint parts) public view returns (uint expected) {
uint _balance = IERC20(_token).balanceOf(_strategy);//11111 1111111
address _want = IGOFStrategy(_strategy).want();//11111111.
(expected,) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function yearn(address _strategy, address _token, uint parts) public {
require(msg.sender == strategist || msg.sender == governance, "Golff:!governance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
// This contract should never have value in it, but just incase since this is a public call
uint _before = IERC20(_token).balanceOf(address(this));
IGOFStrategy(_strategy).withdraw(_token);
uint _after = IERC20(_token).balanceOf(address(this));
if (_after > _before) {
uint _amount = _after.sub(_before);
address _want = IGOFStrategy(_strategy).want();
uint[] memory _distribution;
uint _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_token).safeApprove(onesplit, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
IERC20(_token).safeApprove(onesplit, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_after = IERC20(_want).balanceOf(address(this));
if (_after > _before) {
_amount = _after.sub(_before);
uint _reward = _amount.mul(split).div(max); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
earn(_want, _amount.sub(_reward));
IERC20(_want).safeTransfer(rewards, _reward); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
}
/**
* 11
* @param _token token to ben withdraw
* @param _amount amount
*/
function withdraw(address _token, uint _amount) public {
require(msg.sender == vaults[_token], "Golff:!vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
IGOFStrategy(strategies[_token]).withdraw(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
|
11 _token token to ben withdraw _amount amount/
|
function withdraw(address _token, uint _amount) public {
}
| 5,392,492
|
./full_match/11155111/0x7c725f34ac93620D2E085A1b0396cB3292aA4952/sources/contracts/CrowdFunding.sol
|
Get likers of a project
|
function getLikers(uint _projectId) public view returns (address[] memory) {
Project storage project = projects[_projectId];
return project.likers;
}
| 3,826,598
|
./partial_match/1/0xd156a09704171AFe371572D4Aece2F75112B9677/sources/src/GasTankModule.sol
|
Gets the list of safes where the `_delegate` is such. _delegate The delegate address./
|
function getDelegatedSafes(address _delegate) public view returns (address[] memory) {
return delegatedGasTanks[_delegate].values();
}
| 9,412,627
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error For CHRTY Tokens And Ethereum
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
/// @return total amount of tokens
function totalSupply() public constant returns (uint256 supply);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint public decimals;
string public name;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @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));
owner = newOwner;
}
}
contract Gateway is Ownable{
using SafeMath for uint;
address public feeAccount1 = 0x455f19F16ee2f3F487fb498A24E3F69f78E8Ec14; //the account1 that will receive fees
address public feeAccount2 = 0x07fe839AD214433B764ca17290Ee966106B7b3C1; //the account2 that will receive fees
address public feeAccountToken = 0xAc159594c06bD64928199B0F4D6D801C447d51D2; //the account that will receive fees tokens
struct BuyInfo {
address buyerAddress;
address sellerAddress;
uint value;
address currency;
}
mapping(address => mapping(uint => BuyInfo)) public payment;
uint balanceFee;
uint public feePercent;
uint public maxFee;
constructor() public{
feePercent = 1500000; // decimals 6. 1.5% fee by default
maxFee = 3000000; // fee can not exceed 3%
}
function getBuyerAddressPayment(address _sellerAddress, uint _orderId) public constant returns(address){
return payment[_sellerAddress][_orderId].buyerAddress;
}
function getSellerAddressPayment(address _sellerAddress, uint _orderId) public constant returns(address){
return payment[_sellerAddress][_orderId].sellerAddress;
}
function getValuePayment(address _sellerAddress, uint _orderId) public constant returns(uint){
return payment[_sellerAddress][_orderId].value;
}
function getCurrencyPayment(address _sellerAddress, uint _orderId) public constant returns(address){
return payment[_sellerAddress][_orderId].currency;
}
function setFeeAccount1(address _feeAccount1) onlyOwner public{
feeAccount1 = _feeAccount1;
}
function setFeeAccount2(address _feeAccount2) onlyOwner public{
feeAccount2 = _feeAccount2;
}
function setFeeAccountToken(address _feeAccountToken) onlyOwner public{
feeAccountToken = _feeAccountToken;
}
function setFeePercent(uint _feePercent) onlyOwner public{
require(_feePercent <= maxFee);
feePercent = _feePercent;
}
function payToken(address _tokenAddress, address _sellerAddress, uint _orderId, uint _value) public returns (bool success){
require(_tokenAddress != address(0));
require(_sellerAddress != address(0));
require(_value > 0);
Token token = Token(_tokenAddress);
require(token.allowance(msg.sender, this) >= _value);
token.transferFrom(msg.sender, feeAccountToken, _value.mul(feePercent).div(100000000));
token.transferFrom(msg.sender, _sellerAddress, _value.sub(_value.mul(feePercent).div(100000000)));
payment[_sellerAddress][_orderId] = BuyInfo(msg.sender, _sellerAddress, _value, _tokenAddress);
success = true;
}
function payEth(address _sellerAddress, uint _orderId, uint _value) internal returns (bool success){
require(_sellerAddress != address(0));
require(_value > 0);
uint fee = _value.mul(feePercent).div(100000000);
_sellerAddress.transfer(_value.sub(fee));
balanceFee = balanceFee.add(fee);
payment[_sellerAddress][_orderId] = BuyInfo(msg.sender, _sellerAddress, _value, 0x0000000000000000000000000000000000000001);
success = true;
}
function transferFee() onlyOwner public{
uint valfee1 = balanceFee.div(2);
feeAccount1.transfer(valfee1);
balanceFee = balanceFee.sub(valfee1);
feeAccount2.transfer(balanceFee);
balanceFee = 0;
}
function balanceOfToken(address _tokenAddress, address _Address) public constant returns (uint) {
Token token = Token(_tokenAddress);
return token.balanceOf(_Address);
}
function balanceOfEthFee() public constant returns (uint) {
return balanceFee;
}
function bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function() external payable {
require(msg.data.length == 20);
require(msg.value > 99999999999);
address sellerAddress = bytesToAddress(bytes(msg.data));
uint value = msg.value.div(10000000000).mul(10000000000);
uint orderId = msg.value.sub(value);
balanceFee = balanceFee.add(orderId);
payEth(sellerAddress, orderId, value);
}
}
|
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
|
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
| 59,499
|
/**
*Submitted for verification at Etherscan.io on 2021-04-07
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <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/IERC721Enumerable.sol
pragma solidity >=0.6.2 <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/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, 'ERC165: invalid interface id');
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'SafeMath: subtraction overflow');
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: modulo by zero');
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
'Address: insufficient balance'
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(
success,
'Address: unable to send value, recipient may have reverted'
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'Address: low-level call with value failed'
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'Address: insufficient balance for call'
);
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
'Address: low-level static call failed'
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), 'Address: static call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
'Address: low-level delegate call failed'
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: delegate call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
'EnumerableMap: index out of bounds'
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, 'EnumerableMap: nonexistent key'); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
'ERC721: balance query for the zero address'
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
'ERC721: owner query for nonexistent token'
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, 'ERC721: approval to current owner');
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
'ERC721: approve caller is not owner nor approved for all'
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
'ERC721: approved query for nonexistent token'
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), 'ERC721: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
'ERC721: operator query for nonexistent token'
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, '');
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
'ERC721: transfer of token that is not own'
); // internal owner
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
'ERC721Metadata: URI set of nonexistent token'
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
'ERC721: transfer to non ERC721Receiver implementer'
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity >=0.6.0 <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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: contracts/RareFractal.sol
pragma solidity >=0.6.12;
contract RareFractal is ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address owner;
mapping(string => uint8) myTokenURI;
mapping(uint256 => Art) public tokenArt;
uint256 public constant MAX_NFT_SUPPLY = 500;
string metadataURL;
struct Art {
string metadata;
string image;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor() public ERC721('RareFractal', 'RAF') {
owner = msg.sender;
}
// EVENTS
event TokenBought(uint256 mintedTokenID, string metadata, string image);
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Mints RareFractal
*/
function mint(
string memory _myTokenURI,
string memory _metadata,
string memory _image
) public payable {
require(_tokenIds.current() < MAX_NFT_SUPPLY, 'Sale has already ended');
require(myTokenURI[_myTokenURI] != 1, 'Token URI is already minted');
require(getNFTPrice() == msg.value, 'Ether value sent is not correct');
// mark token URI as minted
myTokenURI[_myTokenURI] = 1;
// new token id
uint256 newItemId = _tokenIds.current();
// save art on chain
tokenArt[newItemId].metadata = _metadata;
tokenArt[newItemId].image = _image;
// mint token && assign ownership of token to address
_safeMint(msg.sender, newItemId);
// set token url
_setTokenURI(newItemId, _myTokenURI);
// emit TokenBought event
emit TokenBought(newItemId, _metadata, _image);
// increment token counter for sold token
_tokenIds.increment();
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() public payable onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Reads Token Art and Metadata from the contract
*/
function getTokenArt(uint256 _tokenID)
public
view
returns (string memory, string memory)
{
require(_tokenID <= _tokenIds.current());
return (tokenArt[_tokenID].metadata, tokenArt[_tokenID].image);
}
/**
* @dev Gets Contract Metadata URL
*/
function contractURI() public view returns (string memory) {
return metadataURL;
}
/**
* @dev Updates the Contract Metadata URL
*/
function contractURI(string memory _metadataURL) public onlyOwner {
metadataURL = _metadataURL;
}
/**
* @dev Gets current RareFractalTree Price
*/
function getNFTPrice() public view returns (uint256) {
require(_tokenIds.current() < MAX_NFT_SUPPLY, 'Sale has already ended');
uint256 currentSupply = _tokenIds.current();
if (currentSupply > 450) {
return 6400000000000000000; // 451 - 500 6.4 ETH
} else if (currentSupply > 375) {
return 3200000000000000000; // 376 - 450 3.2 ETH
} else if (currentSupply > 300) {
return 1600000000000000000; // 301 - 375 1.6 ETH
} else if (currentSupply > 225) {
return 800000000000000000; // 226 - 300 0.8 ETH
} else if (currentSupply > 150) {
return 400000000000000000; // 151 - 225 0.4 ETH
} else if (currentSupply > 75) {
return 200000000000000000; // 76 - 150 0.2 ETH
} else {
return 100000000000000000; // 0 - 75 0.1 ETH
}
}
}
|
Approve `to` to operate on `tokenId` Emits an {Approval} event./
|
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
'ERC721: transfer to non ERC721Receiver implementer'
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
}
| 2,381,193
|
pragma solidity ^0.4.17;
contract DeviceContract {
using SafeMath for uint256;
event DeviceCreated(uint256 tokenId, string name, address owner);
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Trigger(uint256 tokenId, int state);
address public ceoAddress;
uint256 private totalDevices;
struct Device {
address owner;
string deviceName;
string deviceType;
int state;
}
Device[] private devices;
function DeviceContract() public {
ceoAddress = msg.sender;
}
/// @dev A mapping from drawings IDs to the address that owns them. All devices have
/// some valid owner address.
mapping (uint256 => address) public deviceIndexToOwner;
/// @dev A mapping from deviceId to an address that has been approved to call
/// transferFrom(). Each device can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public deviceIndexToApproved;
// @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 Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return totalDevices;
}
function addDevice(string _name) public {
_createDevice(_name, msg.sender);
}
function _createDevice(string _name, address _owner) private {
Device memory _device = Device({
owner: _owner,
deviceName: _name,
deviceType: "lightbulb",
state: 0
});
uint256 newDeviceId = devices.push(_device) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newDeviceId == uint256(uint32(newDeviceId)));
emit DeviceCreated(newDeviceId, _name, _owner);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newDeviceId);
totalDevices = totalDevices.add(1);
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
//transfer ownership
deviceIndexToOwner[_tokenId] = _to;
ownershipTokenCount[_to]++;
// When creating new drawing _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete deviceIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
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 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 deviceId;
for (deviceId = 1; deviceId <= totalDevices; deviceId++) {
if (deviceIndexToOwner[deviceId] == _owner) {
result[resultIndex] = deviceId;
resultIndex++;
}
}
return result;
}
}
function getDevice(uint256 _id)
external
view
returns (
address owner,
string deviceName,
string deviceType,
int state
) {
Device storage device = devices[_id];
owner = device.owner;
deviceName = device.deviceName;
deviceType = device.deviceType;
state = device.state;
}
function tiggerDevice(uint256 _id, int _state) public {
devices[_id].state = _state;
emit Trigger(_id, _state);
}
}
/**
* @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 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;
}
}
|
Gets the total amount of tokens stored by the contract return uint256 representing the total amount of tokens/
|
function totalSupply() public view returns (uint256) {
return totalDevices;
}
| 13,098,977
|
/**
*Submitted for verification at Etherscan.io on 2021-02-26
*/
/**
*Submitted for verification at Etherscan.io on 2020-08-26
*/
pragma solidity >=0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(
isMinter(_msgSender()),
"MinterRole: caller does not have the Minter role"
);
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor() internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(
isWhitelistAdmin(_msgSender()),
"WhitelistAdminRole: caller does not have the WhitelistAdmin role"
);
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @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 MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount 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 _amount,
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 MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @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 _amounts,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool isOperator);
}
/**
* Copyright 2018 ZeroEx Intl.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
/**
* @dev Implementation of Multi-Token Standard contract
*/
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping(address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping(address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) public {
require(
(msg.sender == _from) || isApprovedForAll(_from, msg.sender),
"ERC1155#safeTransferFrom: INVALID_OPERATOR"
);
require(
_to != address(0),
"ERC1155#safeTransferFrom: INVALID_RECIPIENT"
);
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) public {
// Requirements
require(
(msg.sender == _from) || isApprovedForAll(_from, msg.sender),
"ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"
);
require(
_to != address(0),
"ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"
);
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount
) internal {
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal {
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval =
IERC1155TokenReceiver(_to).onERC1155Received(
msg.sender,
_from,
_id,
_amount,
_data
);
require(
retval == ERC1155_RECEIVED_VALUE,
"ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"
);
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts
) internal {
require(
_ids.length == _amounts.length,
"ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"
);
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(
_amounts[i]
);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) internal {
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval =
IERC1155TokenReceiver(_to).onERC1155BatchReceived(
msg.sender,
_from,
_ids,
_amounts,
_data
);
require(
retval == ERC1155_BATCH_RECEIVED_VALUE,
"ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"
);
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public
view
returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public
view
returns (uint256[] memory)
{
require(
_owners.length == _ids.length,
"ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"
);
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
{
if (
_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155
) {
return true;
}
return false;
}
}
/**
* @notice Contract that handles metadata related methods.
* @dev Methods assume a deterministic generation of URI based on token IDs.
* Methods also assume that URI uses hex representation of token IDs.
*/
contract ERC1155Metadata {
// URI's default URI prefix
string internal baseMetadataURI;
mapping(uint256 => string) internal ipfsHash;
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) public view returns (string memory) {
return
string(abi.encodePacked(baseMetadataURI, ipfsHash[_id], ".json"));
}
/***********************************|
| Metadata Internal Functions |
|__________________________________*/
/**
* @notice Will emit default URI log event for corresponding token _id
* @param _tokenIDs Array of IDs of tokens to log default URI
*/
function _logURIs(uint256[] memory _tokenIDs) internal {
string memory baseURL = baseMetadataURI;
string memory tokenURI;
for (uint256 i = 0; i < _tokenIDs.length; i++) {
tokenURI = string(
abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")
);
emit URI(tokenURI, _tokenIDs[i]);
}
}
/**
* @notice Will emit a specific URI log event for corresponding token
* @param _tokenIDs IDs of the token corresponding to the _uris logged
* @param _URIs The URIs of the specified _tokenIDs
*/
function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs)
internal
{
require(
_tokenIDs.length == _URIs.length,
"ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
emit URI(_URIs[i], _tokenIDs[i]);
}
}
/**
* @notice Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/***********************************|
| Utility Internal Functions |
|__________________________________*/
/**
* @notice Convert uint256 to string
* @param _i Unsigned integer to convert to string
*/
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 ii = _i;
uint256 len;
// Get number of bytes
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
// Get each individual ASCII
while (ii != 0) {
bstr[k--] = bytes1(uint8(48 + (ii % 10)));
ii /= 10;
}
// Convert to string
return string(bstr);
}
}
/**
* @dev Multi-Fungible Tokens with minting and burning methods. These methods assume
* a parent contract to be executed as they are `internal` functions
*/
contract ERC1155MintBurn is ERC1155 {
/****************************************|
| Minting Functions |
|_______________________________________*/
/**
* @notice Mint _amount of tokens of a given id
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function _mint(
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal {
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
// Emit event
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
// Calling onReceive method if recipient is contract
_callonERC1155Received(address(0x0), _to, _id, _amount, _data);
}
/**
* @notice Mint tokens for each ids in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function _batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) internal {
require(
_ids.length == _amounts.length,
"ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"
);
// Number of mints to execute
uint256 nMint = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nMint; i++) {
// Update storage balance
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts);
// Calling onReceive method if recipient is contract
_callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data);
}
/****************************************|
| Burning Functions |
|_______________________________________*/
/**
* @notice Burn _amount of tokens of a given token id
* @param _from The address to burn tokens from
* @param _id Token id to burn
* @param _amount The amount to be burned
*/
function _burn(
address _from,
uint256 _id,
uint256 _amount
) internal {
//Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
// Emit event
emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount);
}
/**
* @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair
* @param _from The address to burn tokens from
* @param _ids Array of token ids to burn
* @param _amounts Array of the amount to be burned
*/
function _batchBurn(
address _from,
uint256[] memory _ids,
uint256[] memory _amounts
) internal {
require(
_ids.length == _amounts.length,
"ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"
);
// Number of mints to execute
uint256 nBurn = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nBurn; i++) {
// Update storage balance
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(
_amounts[i]
);
}
// Emit batch mint event
emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);
}
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde =
new string(
_ba.length + _bb.length + _bc.length + _bd.length + _be.length
);
bytes memory babcde = bytes(abcde);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address,
* has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is
ERC1155,
ERC1155MintBurn,
ERC1155Metadata,
Ownable,
MinterRole,
WhitelistAdminRole
{
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function removeWhitelistAdmin(address account) public onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(baseMetadataURI, "/", ipfsHash[_id]);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyWhitelistAdmin
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _maxSupply max supply allowed
* @param _initialSupply Optional amount to supply the first owner
* @param _ipfsHash hash of asset in ipfs;
* @param _data Optional data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _ipfsHash,
bytes calldata _data
) external onlyWhitelistAdmin returns (uint256 tokenId) {
require(
_initialSupply <= _maxSupply,
"Initial supply cannot be more than max supply"
);
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
ipfsHash[_id] = _ipfsHash;
emit URI(uri(_id), _id);
return _id;
}
function setIpfsHash(uint256 _id, string calldata _ipfsHash)
external
onlyWhitelistAdmin
returns (bool success)
{
ipfsHash[_id] = _ipfsHash;
emit URI(uri(_id), _id);
success = true;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public onlyMinter {
uint256 tokenId = _id;
require(
tokenSupply[tokenId] < tokenMaxSupply[tokenId],
"Max supply reached"
);
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
/**
* @title MyCollectible
* MyCollectible - a contract for my semi-fungible tokens.
*/
contract CombMeme is ERC1155Tradable {
constructor(address _proxyRegistryAddress)
public
ERC1155Tradable("Combine Meme", "CBM", _proxyRegistryAddress)
{
_setBaseMetadataURI("ipfs://");
}
function contractURI() public pure returns (string memory) {
return "https://api.combineme.me/contract/memes-erc115";
}
}
|
ERC-1155 interface for accepting safe transfers./
|
interface IERC1155TokenReceiver {
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
| 2,214,977
|
pragma solidity ^0.5.7;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line 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);
}
contract EIP20 is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
constructor(
uint256 _initialAmount,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BitbattleExchange{
using SafeMath for uint256;
constructor(address _escrow, address _namiMultiSigWallet) public {
require(_namiMultiSigWallet != address(0));
escrow = _escrow;
namiMultiSigWallet = _namiMultiSigWallet;
// init token
// BinanceCoin
TokenAddress[0] = 0xB8c77482e45F1F44dE1745F52C74426C631bDD52;
// Maker
TokenAddress[1] = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
// BasicAttentionToken
TokenAddress[2] = 0x0D8775F648430679A709E98d2b0Cb6250d2887EF;
// OmiseGo
TokenAddress[3] = 0xd26114cd6EE289AccF82350c8d8487fedB8A0C07;
// Chainlink
TokenAddress[4] = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
// Holo
TokenAddress[5] = 0x6c6EE5e31d828De241282B9606C8e98Ea48526E2;
// Zilliqa
TokenAddress[6] = 0x05f4a42e251f2d52b8ed15E9FEdAacFcEF1FAD27;
// Augur
TokenAddress[7] = 0x1985365e9f78359a9B6AD760e32412f4a445E862;
// 0x
TokenAddress[8] = 0xE41d2489571d322189246DaFA5ebDe1F4699F498;
// THETA
TokenAddress[9] = 0x3883f5e181fccaF8410FA61e12b59BAd963fb645;
// PundiX
TokenAddress[10] = 0xA15C7Ebe1f07CaF6bFF097D8a589fb8AC49Ae5B3;
// IOST
TokenAddress[11] = 0xFA1a856Cfa3409CFa145Fa4e20Eb270dF3EB21ab;
// EnjinCoin
TokenAddress[12] = 0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c;
// HuobiToken
TokenAddress[13] = 0x6f259637dcD74C767781E37Bc6133cd6A68aa161;
// Status
TokenAddress[14] = 0x744d70FDBE2Ba4CF95131626614a1763DF805B9E;
// Nami
TokenAddress[15] = 0x8d80de8A78198396329dfA769aD54d24bF90E7aa;
// Dai
TokenAddress[16] = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
// KyberNetwork
TokenAddress[17] = 0xdd974D5C2e2928deA5F71b9825b8b646686BD200;
// Golem
TokenAddress[18] = 0xa74476443119A942dE498590Fe1f2454d7D4aC0d;
// Populous
TokenAddress[19] = 0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a;
// CryptoCom
TokenAddress[20] = 0xB63B606Ac810a52cCa15e44bB630fd42D8d1d83d;
// Waltonchain
TokenAddress[21] = 0xb7cB1C96dB6B22b0D3d9536E0108d062BD488F74;
// Decentraland
TokenAddress[22] = 0x0F5D2fB29fb7d3CFeE444a200298f468908cC942;
// LoomNetwork
TokenAddress[23] = 0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0;
// Loopring
TokenAddress[24] = 0xEF68e7C694F40c8202821eDF525dE3782458639f;
// Aelf
TokenAddress[25] = 0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e;
// PowerLedger
TokenAddress[26] = 0x595832F8FC6BF59c85C527fEC3740A1b7a361269;
// USDCoin
TokenAddress[27] = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
}
// escrow has exclusive priveleges to call administrative
// functions on this contract.
address public escrow;
uint public minWithdraw = 1 * 10**18;
uint public maxWithdraw = 1000000 * 10**18;
// Gathered funds can be withdraw only to namimultisigwallet's address.
address public namiMultiSigWallet;
// Token Address
mapping(uint256 => address) public TokenAddress;
/**
* list setting function
*/
mapping(address => bool) public isController;
/**
* List event
*/
event Withdraw(address indexed user, uint amount, uint timeWithdraw, uint tokenIndex);
modifier onlyEscrow() {
require(msg.sender == escrow);
_;
}
modifier onlyNamiMultisig {
require(msg.sender == namiMultiSigWallet);
_;
}
modifier onlyController {
require(isController[msg.sender] == true);
_;
}
/**
* Admin function
*/
function() external payable {}
function changeEscrow(address _escrow) public
onlyNamiMultisig
{
require(_escrow != address(0));
escrow = _escrow;
}
function changeMinWithdraw(uint _minWithdraw) public
onlyEscrow
{
require(_minWithdraw != 0);
minWithdraw = _minWithdraw;
}
function changeMaxWithdraw(uint _maxNac) public
onlyEscrow
{
require(_maxNac != 0);
maxWithdraw = _maxNac;
}
/// @dev withdraw ether, only escrow can call
/// @param _amount value ether in wei to withdraw
function withdrawEther(uint _amount, address payable _to) public
onlyEscrow
{
require(_to != address(0x0));
// Available at any phase.
if (address(this).balance > 0) {
_to.transfer(_amount);
}
}
/**
* make new controller
* require input address is not a controller
* execute any time in sc state
*/
function setController(address _controller)
public
onlyEscrow
{
require(!isController[_controller]);
isController[_controller] = true;
}
/**
* remove controller
* require input address is a controller
* execute any time in sc state
*/
function removeController(address _controller)
public
onlyEscrow
{
require(isController[_controller]);
isController[_controller] = false;
}
/**
* update token address
*/
function updateTokenAddress(address payable _tokenAddress, uint _tokenIndex) public
onlyEscrow
{
require(_tokenAddress != address(0));
TokenAddress[_tokenIndex] = _tokenAddress;
}
function withdrawToken(address _account, uint _amount, uint _tokenIndex) public
onlyController
{
require(_account != address(0x0) && _amount != 0);
require(_amount >= minWithdraw && _amount <= maxWithdraw);
// check valid token index
require(TokenAddress[_tokenIndex] != address(0));
EIP20 ERC20Token = EIP20(TokenAddress[_tokenIndex]);
if (ERC20Token.balanceOf(address(this)) >= _amount) {
ERC20Token.transfer(_account, _amount);
} else {
revert();
}
// emit event
emit Withdraw(_account, _amount, now, _tokenIndex);
}
}
|
remove controller require input address is a controller execute any time in sc state/
|
function removeController(address _controller)
public
onlyEscrow
{
require(isController[_controller]);
isController[_controller] = false;
}
| 6,365,885
|
./full_match/97/0xec51816BFE26468dec6931baF37a168637b6D3f5/sources/staking/Staking.sol
|
validator commission rate init validator default params save validator owner add new validator to array
|
function _addValidator(address validatorAddress, address validatorOwner, ValidatorStatus status, uint16 commissionRate, uint256 initialStake, uint64 sinceEpoch) internal {
require(commissionRate >= COMMISSION_RATE_MIN_VALUE && commissionRate <= COMMISSION_RATE_MAX_VALUE, "bad commission");
Validator memory validator = _validatorsMap[validatorAddress];
require(_validatorsMap[validatorAddress].status == ValidatorStatus.NotFound, "already exist");
validator.validatorAddress = validatorAddress;
validator.ownerAddress = validatorOwner;
validator.status = status;
validator.changedAt = sinceEpoch;
_validatorsMap[validatorAddress] = validator;
require(_validatorOwners[validatorOwner] == address(0x00), "owner in use");
_validatorOwners[validatorOwner] = validatorAddress;
if (status == ValidatorStatus.Active) {
_activeValidatorsList.push(validatorAddress);
}
require(delegation.delegateQueue.length == 0);
delegation.delegateQueue.push(DelegationOpDelegate(uint112(initialStake / BALANCE_COMPACT_PRECISION), sinceEpoch));
emit Delegated(validatorAddress, validatorOwner, initialStake, sinceEpoch);
}
| 5,034,381
|
./partial_match/1/0xF77A1E70303A5ff1Eed43ccEA9A983090e6dD823/sources/src/nonz.sol
|
Function to multiply input by 98765
|
function multiplyBy98765(uint256 _input)
public
pure
nonZeroInput(_input)
returns (uint256)
{
return _input * 98765;
}
| 3,727,807
|
pragma ton-solidity >= 0.39.0;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
pragma AbiHeader time;
import './interfaces/ITIP3Deployer.sol';
import './interfaces/ITIP3DeployerManageCode.sol';
import './interfaces/ITIP3DeployerServiceInfo.sol';
import './libraries/TIP3DeployerErrorCodes.sol';
import '../utils/libraries/MsgFlag.sol';
import '../utils/interfaces/IUpgradableContract.sol';
import '../utils/TIP3/RootTokenContract.sol';
contract TIP3TokenDeployer is ITIP3Deployer, ITIP3DeployerManageCode, ITIP3DeployerServiceInfo, IUpgradableContract {
TvmCell rootContractCode;
TvmCell walletContractCode;
address ownerAddress;
uint32 contractCodeVersion;
/*********************************************************************************************************/
// Basic functions for deploy and upgrade
// Contract is deployed using platform
constructor(address _owner) public {
tvm.accept();
ownerAddress = _owner;
}
function upgradeContractCode(TvmCell code, TvmCell updateParams, uint32 codeVersion) override external onlyOwner {
tvm.accept();
tvm.setcode(code);
tvm.setCurrentCode(code);
onCodeUpgrade(
ownerAddress,
rootContractCode,
walletContractCode,
updateParams,
codeVersion
);
}
function onCodeUpgrade(
address,
TvmCell,
TvmCell,
TvmCell,
uint32
) private {
}
/*********************************************************************************************************/
// Functions for TIP-3 token deploy
/**
* @param rootInfo Information required to create TIP-3 token
* @param deployGrams Amount of tons to transfer to root contract
* @param pubkeyToInsert Pubker used for contract
* @param payloadToReturn Payload to return with address of new TIP-3 token (can contain some useful information)
*/
function deployTIP3(IRootTokenContract.IRootTokenContractDetails rootInfo, uint128 deployGrams, uint256 pubkeyToInsert, TvmCell payloadToReturn)
external
responsible
override
checkMsgValue(deployGrams)
returns (address, TvmCell)
{
tvm.rawReserve(msg.value, 2);
address tip3TokenAddress = new RootTokenContract{
value: deployGrams,
flag: 0,
code: rootContractCode,
pubkey: pubkeyToInsert,
varInit: {
_randomNonce: 0,
name: rootInfo.name,
symbol: rootInfo.symbol,
decimals: rootInfo.decimals,
wallet_code: walletContractCode
}
}(rootInfo.root_public_key, rootInfo.root_owner_address);
return { value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS } (tip3TokenAddress, payloadToReturn);
}
/**
* @param rootInfo Information required to create TIP-3 token
* @param pubkeyToInsert Pubkey used for contract
*/
function getFutureTIP3Address(IRootTokenContract.IRootTokenContractDetails rootInfo, uint256 pubkeyToInsert) external override responsible returns (address) {
tvm.accept();
TvmCell stateInit = tvm.buildStateInit({
contr: RootTokenContract,
code: rootContractCode,
pubkey: pubkeyToInsert,
varInit: {
_randomNonce: 0,
name: rootInfo.name,
symbol: rootInfo.symbol,
decimals: rootInfo.decimals,
wallet_code: walletContractCode
}
});
return address.makeAddrStd(0, tvm.hash(stateInit));
}
/*********************************************************************************************************/
// TIP-3 code update functions
/**
* @param _rootContractCode Code of RootTokenContract
*/
function setTIP3RootContractCode(TvmCell _rootContractCode) external override onlyOwner {
tvm.accept();
rootContractCode = _rootContractCode;
}
/**
* @param _walletContractCode Code of TONTokenWallet
*/
function setTIP3WalletContractCode(TvmCell _walletContractCode) external override onlyOwner {
tvm.accept();
walletContractCode = _walletContractCode;
}
function getServiceInfo() external override responsible view returns (ServiceInfo) {
return ServiceInfo(rootContractCode, walletContractCode);
}
/*********************************************************************************************************/
// Modifiers
modifier onlyOwner() {
require(msg.sender == ownerAddress, TIP3DeployerErrorCodes.ERROR_MSG_SENDER_IS_NOT_OWNER);
_;
}
/**
* @param gramsRequired Amount of grams required for deploy
*/
modifier checkMsgValue(uint128 gramsRequired) {
require(msg.value > gramsRequired, TIP3DeployerErrorCodes.ERROR_MSG_VALUE_IS_TOO_LOW);
_;
}
}
|
/ Functions for TIP-3 token deploy rootInfo Information required to create TIP-3 token deployGrams Amount of tons to transfer to root contract pubkeyToInsert Pubker used for contract payloadToReturn Payload to return with address of new TIP-3 token (can contain some useful information)/
|
function deployTIP3(IRootTokenContract.IRootTokenContractDetails rootInfo, uint128 deployGrams, uint256 pubkeyToInsert, TvmCell payloadToReturn)
external
responsible
override
checkMsgValue(deployGrams)
returns (address, TvmCell)
{
tvm.rawReserve(msg.value, 2);
address tip3TokenAddress = new RootTokenContract{
value: deployGrams,
flag: 0,
code: rootContractCode,
pubkey: pubkeyToInsert,
varInit: {
_randomNonce: 0,
name: rootInfo.name,
symbol: rootInfo.symbol,
decimals: rootInfo.decimals,
wallet_code: walletContractCode
}
}(rootInfo.root_public_key, rootInfo.root_owner_address);
}
| 12,895,504
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "./interfaces/IQuantumArt.sol";
import "./interfaces/IQuantumMintPass.sol";
import "./interfaces/IQuantumUnlocked.sol";
import "./interfaces/IQuantumKeyRing.sol";
import "./ContinuousDutchAuction.sol";
import "@rari-capital/solmate/src/auth/Auth.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract SalePlatform is ContinuousDutchAuction, ReentrancyGuard, Auth {
using BitMaps for BitMaps.BitMap;
using Strings for uint256;
struct Sale {
uint128 price;
uint64 start;
uint64 limit;
}
struct MPClaim {
uint64 mpId;
uint64 start;
uint128 price;
}
struct Whitelist {
uint192 price;
uint64 start;
bytes32 merkleRoot;
}
event Purchased(uint256 indexed dropId, uint256 tokenId, address to);
event DropCreated(uint256 dropId);
//mapping dropId => struct
mapping (uint256 => Sale) public sales;
mapping (uint256 => MPClaim) public mpClaims;
mapping (uint256 => Whitelist) public whitelists;
uint256 public defaultArtistCut; //10000 * percentage
IQuantumArt public quantum;
IQuantumMintPass public mintpass;
IQuantumUnlocked public keyUnlocks;
IQuantumKeyRing public keyRing;
address[] public privilegedContracts;
BitMaps.BitMap private _disablingLimiter;
mapping (uint256 => BitMaps.BitMap) private _claimedWL;
mapping (address => BitMaps.BitMap) private _alreadyBought;
mapping (uint256 => uint256) private _overridedArtistCut; // dropId -> cut
address payable private _quantumTreasury;
//TODO: Better drop mechanism
struct UnlockSale {
uint128 price;
uint64 start;
uint64 period;
address artist;
uint256 overrideArtistcut;
uint256[] enabledKeyRanges;
}
uint private constant SEPARATOR = 10**4;
uint128 private _nextUnlockDropId;
//TODO: CLEAN UP
mapping(uint256 => mapping(uint256 => bool)) keyUnlockClaims;
//TODO: Seperate sales mechanisms for target sales is not right.
mapping (uint256 => UnlockSale) public keySales;
constructor(
address deployedQuantum,
address deployedMP,
address deployedKeyRing,
address deployedUnlocks,
address admin,
address payable treasury,
address authority) Auth(admin, Authority(authority)) {
quantum = IQuantumArt(deployedQuantum);
mintpass = IQuantumMintPass(deployedMP);
keyRing = IQuantumKeyRing(deployedKeyRing);
keyUnlocks = IQuantumUnlocked(deployedUnlocks);
_quantumTreasury = treasury;
defaultArtistCut = 8000; //default 80% for artist
}
modifier checkCaller {
require(msg.sender.code.length == 0, "Contract forbidden");
_;
}
modifier isFirstTime(uint256 dropId) {
if (!_disablingLimiter.get(dropId)) {
require(!_alreadyBought[msg.sender].get(dropId), string(abi.encodePacked("Already bought drop ", dropId.toString())));
_alreadyBought[msg.sender].set(dropId);
}
_;
}
function setPrivilegedContracts(address[] calldata contracts) requiresAuth public {
privilegedContracts = contracts;
}
function withdraw(address payable to) requiresAuth public {
Address.sendValue(to, address(this).balance);
}
function premint(uint256 dropId, address[] calldata recipients) requiresAuth public {
for(uint256 i = 0; i < recipients.length; i++) {
uint256 tokenId = quantum.mintTo(dropId, recipients[i]);
emit Purchased(dropId, tokenId, recipients[i]);
}
}
function setMintpass(address deployedMP) requiresAuth public {
mintpass = IQuantumMintPass(deployedMP);
}
function setQuantum(address deployedQuantum) requiresAuth public {
quantum = IQuantumArt(deployedQuantum);
}
function setKeyRing(address deployedKeyRing) requiresAuth public {
keyRing = IQuantumKeyRing(deployedKeyRing);
}
function setKeyUnlocks(address deployedUnlocks) requiresAuth public {
keyUnlocks = IQuantumUnlocked(deployedUnlocks);
}
function setDefaultArtistCut(uint256 cut) requiresAuth public {
defaultArtistCut = cut;
}
function createSale(uint256 dropId, uint128 price, uint64 start, uint64 limit) requiresAuth public {
sales[dropId] = Sale(price, start, limit);
}
function createMPClaim(uint256 dropId, uint64 mpId, uint64 start, uint128 price) requiresAuth public {
mpClaims[dropId] = MPClaim(mpId, start, price);
}
function createWLClaim(uint256 dropId, uint192 price, uint64 start, bytes32 root) requiresAuth public {
whitelists[dropId] = Whitelist(price, start, root);
}
function flipUint64(uint64 x) internal pure returns (uint64) {
return x > 0 ? 0 : type(uint64).max;
}
function flipSaleState(uint256 dropId) requiresAuth public {
sales[dropId].start = flipUint64(sales[dropId].start);
}
function flipMPClaimState(uint256 dropId) requiresAuth public {
mpClaims[dropId].start = flipUint64(mpClaims[dropId].start);
}
function flipWLState(uint256 dropId) requiresAuth public {
whitelists[dropId].start = flipUint64(whitelists[dropId].start);
}
function flipLimiterForDrop(uint256 dropId) requiresAuth public {
if (_disablingLimiter.get(dropId)) {
_disablingLimiter.unset(dropId);
} else {
_disablingLimiter.set(dropId);
}
}
function overrideArtistcut(uint256 dropId, uint256 cut) requiresAuth public {
_overridedArtistCut[dropId] = cut;
}
function overrideUnlockArtistCut(uint256 dropId, uint256 cut) requiresAuth public {
keySales[dropId].overrideArtistcut = cut;
}
function setAuction(
uint256 auctionId,
uint256 startingPrice,
uint128 decreasingConstant,
uint64 start,
uint64 period
) public override requiresAuth {
super.setAuction(auctionId, startingPrice, decreasingConstant, start, period);
}
function curatedPayout(address artist, uint256 dropId, uint256 amount) internal {
uint256 artistCut = _overridedArtistCut[dropId] == 0 ? defaultArtistCut : _overridedArtistCut[dropId];
uint256 payout_ = (amount*artistCut)/10000;
Address.sendValue(payable(artist), payout_);
Address.sendValue(_quantumTreasury, amount - payout_);
}
function genericPayout(address artist, uint256 amount, uint256 cut) internal {
uint256 artistCut = cut == 0 ? defaultArtistCut : cut;
uint256 payout_ = (amount*artistCut)/10000;
Address.sendValue(payable(artist), payout_);
Address.sendValue(_quantumTreasury, amount - payout_);
}
function _isPrivileged(address user) internal view returns (bool) {
uint256 length = privilegedContracts.length;
unchecked {
for(uint i; i < length; i++) {
/// @dev using this interface because has balanceOf
if (IQuantumArt(privilegedContracts[i]).balanceOf(user) > 0) {
return true;
}
}
}
return false;
}
function purchase(uint256 dropId, uint256 amount) nonReentrant checkCaller isFirstTime(dropId) payable public {
Sale memory sale = sales[dropId];
require(block.timestamp >= sale.start, "PURCHASE:SALE INACTIVE");
require(amount <= sale.limit, "PURCHASE:OVER LIMIT");
require(msg.value == amount * sale.price, "PURCHASE:INCORRECT MSG.VALUE");
for(uint256 i = 0; i < amount; i++) {
uint256 tokenId = quantum.mintTo(dropId, msg.sender);
emit Purchased(dropId, tokenId, msg.sender);
}
curatedPayout(quantum.getArtist(dropId), dropId, msg.value);
}
function purchaseThroughAuction(uint256 dropId) nonReentrant checkCaller isFirstTime(dropId) payable public {
Auction memory auction = _auctions[dropId];
// if 5 minutes before public auction
// if holder -> special treatment
uint256 userPaid = auction.startingPrice;
if (
block.timestamp <= auction.start &&
block.timestamp >= auction.start - 300 &&
_isPrivileged(msg.sender)
) {
require(msg.value == userPaid, "PURCHASE:INCORRECT MSG.VALUE");
} else {
userPaid = verifyBid(dropId);
}
uint256 tokenId = quantum.mintTo(dropId, msg.sender);
emit Purchased(dropId, tokenId, msg.sender);
curatedPayout(quantum.getArtist(dropId), dropId, userPaid);
}
function unlockWithKey(uint256 keyId, uint128 dropId, uint256 variant) nonReentrant checkCaller payable public {
require(keyRing.ownerOf(keyId) == msg.sender, "PURCHASE:NOT KEY OWNER");
require(!keyUnlockClaims[dropId][keyId], "PURCHASE:KEY ALREADY USED");
require(variant>0 && variant<13, "PURCHASE:INVALID VARIANT");
UnlockSale memory sale = keySales[dropId];
//Check is a valid key range (to limit to particular keys)
bool inRange = false;
if (sale.enabledKeyRanges.length > 0) {
for (uint256 i=0; i<sale.enabledKeyRanges.length; i++) {
if ((keyId >= (sale.enabledKeyRanges[i] * SEPARATOR)) && (keyId < (((sale.enabledKeyRanges[i]+1) * SEPARATOR)-1))) inRange = true;
}
}
else inRange = true;
require(inRange, "PURCHASE:SALE NOT AVAILABLE TO THIS KEY");
require(block.timestamp >= sale.start, "PURCHASE:SALE NOT STARTED");
require(block.timestamp <= (sale.start + sale.period), "PURCHASE:SALE EXPIRED");
require(msg.value == sale.price, "PURCHASE:INCORRECT MSG.VALUE");
uint256 tokenId = keyUnlocks.mint(msg.sender, dropId, variant);
keyUnlockClaims[dropId][keyId] = true;
emit Purchased(dropId, tokenId, msg.sender);
genericPayout(sale.artist, msg.value, sale.overrideArtistcut);
}
function createUnlockSale(uint128 price, uint64 start, uint64 period, address artist, uint256[] calldata enabledKeyRanges) requiresAuth public {
emit DropCreated(_nextUnlockDropId);
uint256[] memory blankRanges;
keySales[_nextUnlockDropId++] = UnlockSale(price, start, period, artist, 0, blankRanges);
for (uint i=0; i<enabledKeyRanges.length; i++) keySales[_nextUnlockDropId-1].enabledKeyRanges.push(enabledKeyRanges[i]);
}
function isKeyUsed(uint256 dropId, uint256 keyId) public view returns (bool) {
return keyUnlockClaims[dropId][keyId];
}
function claimWithMintPass(uint256 dropId, uint256 amount) nonReentrant payable public {
MPClaim memory mpClaim = mpClaims[dropId];
require(block.timestamp >= mpClaim.start, "MP: CLAIMING INACTIVE");
require(msg.value == amount * mpClaim.price, "MP:WRONG MSG.VALUE");
mintpass.burnFromRedeem(msg.sender, mpClaim.mpId, amount); //burn mintpasses
for(uint256 i = 0; i < amount; i++) {
uint256 tokenId = quantum.mintTo(dropId, msg.sender);
emit Purchased(dropId, tokenId, msg.sender);
}
if (msg.value > 0) curatedPayout(quantum.getArtist(dropId), dropId, msg.value);
}
function purchaseThroughWhitelist(uint256 dropId, uint256 amount, uint256 index, bytes32[] calldata merkleProof) nonReentrant external payable {
Whitelist memory whitelist = whitelists[dropId];
require(block.timestamp >= whitelist.start, "WL:INACTIVE");
require(msg.value == whitelist.price * amount, "WL: INVALID MSG.VALUE");
require(!_claimedWL[dropId].get(index), "WL:ALREADY CLAIMED");
bytes32 node = keccak256(abi.encodePacked(msg.sender, amount, index));
require(MerkleProof.verify(merkleProof, whitelist.merkleRoot, node),"WL:INVALID PROOF");
_claimedWL[dropId].set(index);
uint256 tokenId = quantum.mintTo(dropId, msg.sender);
emit Purchased(dropId, tokenId, msg.sender);
curatedPayout(quantum.getArtist(dropId), dropId, msg.value);
}
function isWLClaimed(uint256 dropId, uint256 index) public view returns (bool) {
return _claimedWL[dropId].get(index);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IQuantumArt {
function mintTo(uint256 dropId, address artist) external returns (uint256);
function burn(uint256 tokenId) external;
function getArtist(uint256 dropId) external view returns (address);
function balanceOf(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IQuantumMintPass {
function burnFromRedeem(address user, uint256 mpId, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IQuantumUnlocked {
function mint(address to, uint128 dropId, uint256 variant) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IQuantumKeyRing {
function make(address to, uint256 id, uint256 amount) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/utils/Address.sol";
abstract contract ContinuousDutchAuction {
struct Auction {
uint256 startingPrice;
uint128 decreasingConstant;
uint64 start;
uint64 period; //period in seconds : MAX IS 18 HOURS
}
mapping (uint => Auction) internal _auctions;
function auctions(uint256 auctionId) public view returns (
uint256 startingPrice,
uint128 decreasingConstant,
uint64 start,
uint64 period,
bool active
) {
Auction memory auction = _auctions[auctionId];
startingPrice = auction.startingPrice;
decreasingConstant = auction.decreasingConstant;
start = auction.start;
period = auction.period;
active = start > 0 && block.timestamp >= start;
}
function setAuction(
uint256 auctionId,
uint256 startingPrice,
uint128 decreasingConstant,
uint64 start,
uint64 period
) virtual public {
unchecked {
require(startingPrice - decreasingConstant * period <= startingPrice, "setAuction: floor price underflow");
}
_auctions[auctionId] = Auction(startingPrice, decreasingConstant, start, period);
}
function getPrice(uint256 auctionId) virtual public view returns (uint256 price) {
Auction memory auction = _auctions[auctionId];
//only compute correct price if necessary
if (block.timestamp < auction.start) price = auction.startingPrice;
else if (block.timestamp >= auction.start + auction.period) price = auction.startingPrice - auction.period * auction.decreasingConstant;
else price = auction.startingPrice - (auction.decreasingConstant * (block.timestamp - auction.start));
}
function verifyBid(uint256 auctionId) internal returns (uint256) {
Auction memory auction = _auctions[auctionId];
require(auction.start > 0, "AUCTION:NOT CREATED");
require(block.timestamp >= auction.start, "PURCHASE:AUCTION NOT STARTED");
uint256 pricePaid = getPrice(auctionId);
require(msg.value >= pricePaid, "PURCHASE:INCORRECT MSG.VALUE");
if (msg.value - pricePaid > 0) Address.sendValue(payable(msg.sender), msg.value-pricePaid); //refund difference
return pricePaid;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/structs/BitMaps.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*/
library BitMaps {
struct BitMap {
mapping(uint256 => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(
BitMap storage bitmap,
uint256 index,
bool value
) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// 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);
}
}
}
}
|
only compute correct price if necessary
|
function getPrice(uint256 auctionId) virtual public view returns (uint256 price) {
Auction memory auction = _auctions[auctionId];
if (block.timestamp < auction.start) price = auction.startingPrice;
else if (block.timestamp >= auction.start + auction.period) price = auction.startingPrice - auction.period * auction.decreasingConstant;
else price = auction.startingPrice - (auction.decreasingConstant * (block.timestamp - auction.start));
}
| 330,868
|
contract WeiFund {
/// @notice New Campaign; create a new crowdfunding campaign
/// @dev This method starts a new crowdfunding campaign and calles the campaigns configuration contract if stated
/// @param _name The campaign name
/// @param _beneficiary The address of the beneficiary for this campaign
/// @param _fundingGoal The funding goal of the campaign. If this goal is not met by the timelimit, all ether will be refunded to the respective contributers
/// @param _expiry When the campaign will expire and contributions can no longer be made
/// @param _config The configuration address
function newCampaign(string _name, address _beneficiary, uint _fundingGoal, uint _expiry, address _config) {}
/// @notice Contribute (the campaign ID); contribute ether to a WeiFund campaign
/// @dev This method will contribute an amount of ether to the campaign at ID _cid. All contribution data will be stored so that the issuance of digital assets can be made out to the contributor address
/// @param _campaignID (Campaign ID) The ID number of the crowdfunding campaign
/// @param _beneficiary (Contribute As Address) This allows a user to contribute on behalf of another address, if left empty, the from sender address is used as the primary Funder address
function contribute(uint _campaignID, address _beneficiary) {}
/// @notice Refund (the campaign ID); refund your contribution of a failed or expired crowdfunding campaign.
/// @dev This method will refund the amount you contributed to a WeiFund campaign, if that campaign has failed to meet it's funding goal or has expired.
/// @param _campaignID (Campaign ID) The ID number of the crowdfunding campaign to be refunded
function refund(uint _campaignID) {}
/// @notice Payout (the campaign ID); this will payout a successfull crowdfunding campaign to the benificiary address
/// @dev This method will payout a successfull WeiFund crowdfunding campaign to the benificiary address specified. Any person can trigger the payout by calling this method.
/// @param _campaignID (Campaign ID) The ID number of the crowdfunding campaign
function payout(uint _campaignID) {}
/// @notice User Campaign ID (the address of the user, the user campaign ID); get the campaign ID of one of the users crowdfunding campaigns.
/// @dev This method will get the campaign ID of one of the users crowdfunding campaigns, by looking up the campaign with a user campaign ID. All campaign owners and their campaigns are stored with WeiFund.
/// @param _user The address of the campaign operator.
/// @param _userCampaignID The user campaign ID
/// @return _campaignID The campaign ID
function userCampaignID(address _user, uint _userCampaignID) constant returns (uint _campaignID) {}
/// @notice Total Number of Campaigns Started for a Given User
/// @dev This method will get the campaign ID of one of the users crowdfunding campaigns, by looking up the campaign with a user campaign ID. All campaign owners and their campaigns are stored with WeiFund.
/// @param _user The user's address
/// @return _numCampaigns The number of campaigns
function totalUserCampaigns(address _user) constant returns (uint _numCampaigns) {}
/// @notice The total number of campaigns on WeiFund
/// @dev This method returns the total number of campaigns on WeiFund as an unsigned integer
/// @return _numCampaigns The number of campaigns
function totalCampaigns() constant returns (uint _numCampaigns) {}
/// @notice Contributor At ID;
/// @dev For retrieving the contributor data at a specific contributor ID
/// @param _campaignID The address of the campaign operator.
/// @param _contributorID The user campaign ID
/// @return _contributor, _beneficiary, _amountContributed, _refunded
function contributorAt(uint _campaignID, uint _contributorID) constant returns (address _contributor,
address _beneficiary,
uint _amountContributed,
bool _refunded){}
function createdAt(uint _campaignID) public constant returns (uint){}
function contributorID(uint _campaignID, address _contributor) constant returns (uint) {}
function ownerOf(uint _campaignID) constant returns (address){}
function beneficiaryOf(uint _campaignID) constant returns (address){}
function configOf(uint _campaignID) constant returns (address){}
function amountRaisedBy(uint _campaignID) constant returns (uint){}
function fundingGoalOf(uint _campaignID) constant returns (uint){}
function expiryOf(uint _campaignID) constant returns (uint){}
function totalContributors(uint _campaignID) constant returns (uint){}
function isContributor(uint _campaignID, address _contributor) constant returns (bool) {}
function isOwner(uint _campaignID, address _owner) constant returns (bool){}
function hasFailed(uint _campaignID) constant returns (bool){}
function isSuccess(uint _campaignID) constant returns (bool){}
function isPaidOut(uint _campaignID) constant returns (bool){}
function totalRefunded(uint _campaignID) constant returns (uint){}
function isRefunded(uint _campaignID) constant returns (bool){}
event CampaignCreated(address indexed _owner, uint indexed _campaignID);
event Contributed(address indexed _contributor, uint indexed _campaignID, uint _amountContributed);
event PaidOut(address indexed _beneficiary, uint indexed _campaignID, uint _amountPaid);
event Refunded(address indexed _contributor, uint indexed _campaignID, uint _amountRefunded);
}
contract WeiHashInterface {
function register(uint _campaignID, bytes _hash){}
function unregister(uint _campaignID){}
function hashOf(uint _campaignID) constant returns (bytes) {}
event HashRegistered(uint indexed _campaignID, address _owner);
event HashDeregistered(uint indexed _campaignID, address _owner);
}
contract WeiHash is WeiHashInterface {
mapping(uint => bytes) public hashes;
address public weifundAddr;
uint public version;
function WeiHash(address _weifundAddr) {
weifundAddr = _weifundAddr;
version = 1;
}
function register(uint _campaignID, bytes _hash){
if(!WeiFund(weifundAddr).isOwner(_campaignID, msg.sender))
throw;
hashes[_campaignID] = _hash;
HashRegistered(_campaignID, msg.sender);
}
function unregister(uint _campaignID, bytes _hash){
if(!WeiFund(weifundAddr).isOwner(_campaignID, msg.sender))
throw;
hashes[_campaignID] = _hash;
HashDeregistered(_campaignID, msg.sender);
}
function hashOf(uint _campaignID) public constant returns (bytes){
return hashes[_campaignID];
}
}
|
The total number of campaigns on WeiFund This method returns the total number of campaigns on WeiFund as an unsigned integer return _numCampaigns The number of campaigns
|
function totalCampaigns() constant returns (uint _numCampaigns) {}
| 13,008,203
|
pragma solidity ^0.4.23;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
// File: contracts/JetwingToken.sol
/*
* JetwingToken is a standard ERC20 token with some additional functionalities:
* - Transfers are only enabled after contract owner enables it (after the ICO)
* - Contract sets 40% of the total supply as allowance for ICO contract
*
* Note: Token Offering == Initial Coin Offering(ICO)
*/
contract JetwingToken is StandardToken, BurnableToken, Ownable {
string public constant symbol = "JETWING";
string public constant name = "JETWING CHAIN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 12000000000 * (10 ** uint256(decimals));
uint256 public constant TOKEN_OFFERING_ALLOWANCE = 4800000000 * (10 ** uint256(decimals));
uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE;
// Address of token admin
address public adminAddr;
// Address of token offering
address public tokenOfferingAddr;
// Enable transfers after conclusion of token offering
bool public transferEnabled = true;
/**
* Check if transfer is allowed
*
* Permissions:
* Owner Admin OfferingContract Others
* transfer (before transferEnabled is true) x x x x
* transferFrom (before transferEnabled is true) x o o x
* transfer/transferFrom(after transferEnabled is true) o x x o
*/
modifier onlyWhenTransferAllowed() {
require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr);
_;
}
/**
* Check if token offering address is set or not
*/
modifier onlyTokenOfferingAddrNotSet() {
require(tokenOfferingAddr == address(0x0));
_;
}
/**
* Check if address is a valid destination to transfer tokens to
* - must not be zero address
* - must not be the token address
* - must not be the owner's address
* - must not be the admin's address
* - must not be the token offering contract address
*/
modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
require(to != address(adminAddr));
require(to != address(tokenOfferingAddr));
_;
}
/**
* Token contract constructor
*
* @param admin Address of admin account
*/
function JetwingToken(address admin) public {
totalSupply_ = INITIAL_SUPPLY;
// Mint tokens
balances[msg.sender] = totalSupply_;
Transfer(address(0x0), msg.sender, totalSupply_);
// Approve allowance for admin account
adminAddr = admin;
approve(adminAddr, ADMIN_ALLOWANCE);
}
/**
* Set token offering to approve allowance for offering contract to distribute tokens
*
* @param offeringAddr Address of token offering contract
* @param amountForSale Amount of tokens for sale, set 0 to max out
*/
function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet {
require(!transferEnabled);
uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale;
require(amount <= TOKEN_OFFERING_ALLOWANCE);
approve(offeringAddr, amount);
tokenOfferingAddr = offeringAddr;
}
/**
* Enable transfers
*/
function enableTransfer() external onlyOwner {
transferEnabled = true;
// End the offering
approve(tokenOfferingAddr, 0);
}
/**
* Transfer from sender to another account
*
* @param to Destination address
* @param value Amount of jetwingtokens to send
*/
function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
return super.transfer(to, value);
}
/**
* Transfer from `from` account to `to` account using allowance in `from` account to the sender
*
* @param from Origin address
* @param to Destination address
* @param value Amount of jetwingtokens to send
*/
function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* Burn token, only owner is allowed to do this
*
* @param value Amount of tokens to burn
*/
function burn(uint256 value) public {
require(transferEnabled || msg.sender == owner);
super.burn(value);
}
}
|
Token contract constructor admin Address of admin account/ Mint tokens Approve allowance for admin account
|
function JetwingToken(address admin) public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = totalSupply_;
Transfer(address(0x0), msg.sender, totalSupply_);
adminAddr = admin;
approve(adminAddr, ADMIN_ALLOWANCE);
}
| 7,932,700
|
./full_match/1/0x6E89Fd91e093691d2e3071e52898dd7Df725a9C3/sources/contracts/TTMarketplace.sol
|
Use in memory variable for everything except when we need to persist data change For gas savings
|
function _deleteList(uint256 _sellId) internal returns (bool) {
SellList memory _sale = sales[_sellId];
if (_sale.isSold == true) {
revert ListingAlreadySold();
}
if (_sale.amountofTokenSold > 0) {
revert SomeTokensAlreadySold();
}
userTokensForSale[_sale.seller][_sale.tokenId] -= _sale.amountOfToken;
_sale.seller,
_sellId,
_sale.tokenId,
_sale.amountOfToken
);
return true;
}
| 17,015,160
|
//SPDX-License-Identifier: MIT
//Copyright 2021 Louis Sobel
pragma solidity ^0.8.0;
/*
88888888ba, 88888888ba 888b 88 88888888888 888888888888
88 `"8b 88 "8b 8888b 88 88 88
88 `8b 88 ,8P 88 `8b 88 88 88
88 88 88aaaaaa8P' 88 `8b 88 88aaaaa 88
88 88 88""""""8b, 88 `8b 88 88""""" 88
88 8P 88 `8b 88 `8b 88 88 88
88 .a8P 88 a8P 88 `8888 88 88
88888888Y"' 88888888P" 88 `888 88 88
https://dbnft.io
Generate NFTs by compiling the DBN language to EVM opcodes, then
deploying a contract that can render your art as a bitmap.
> Line 0 0 100 100
╱
╱
╱
╱
╱
╱
╱
╱
╱
╱
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DBNERC721Enumerable.sol";
import "./OpenSeaTradable.sol";
import "./OwnerSignedTicketRestrictable.sol";
import "./Drawing.sol";
import "./Token.sol";
import "./Serialize.sol";
/**
* @notice Compile DBN drawings to Ethereum Virtual Machine opcodes and deploy the code as NFT art.
* @dev This contract implements the ERC721 (including Metadata and Enumerable extensions)
* @author Louis Sobel
*/
contract DBNCoordinator is Ownable, DBNERC721Enumerable, OpenSeaTradable, OwnerSignedTicketRestrictable {
using Counters for Counters.Counter;
using Strings for uint256;
/**
* @dev There's two ~types of tokenId out of the 10201 (101x101) total tokens
* - 101 "allowlisted ones" [0, 100]
* - And "Open" ones [101, 10200]
* Minting of the allowlisted ones is through mintTokenId function
* Minting of the Open ones is through plain mint
*/
uint256 private constant LAST_ALLOWLISTED_TOKEN_ID = 100;
uint256 private constant LAST_TOKEN_ID = 10200;
/**
* @dev Event emitted when a a token is minted, linking the token ID
* to the address of the deployed drawing contract
*/
event DrawingDeployed(uint256 tokenId, address addr);
// Configuration
enum ContractMode { AllowlistOnly, Open }
ContractMode private _contractMode;
uint256 private _mintPrice;
string private _baseExternalURI;
address payable public recipient;
bool public recipientLocked;
// Minting
Counters.Counter private _tokenIds;
mapping (uint256 => address) private _drawingAddressForTokenId;
/**
* @dev Initializes the contract
* @param owner address to immediately transfer the contract to
* @param baseExternalURI URL (like https//dbnft.io/dbnft/) to which
* tokenIDs will be appended to get the `external_URL` metadata field
* @param openSeaProxyRegistry address of the opensea proxy registry, will
* be saved and queried in isAllowedForAll to facilitate opensea listing
*/
constructor(
address owner,
string memory baseExternalURI,
address payable _recipient,
address openSeaProxyRegistry
) ERC721("Design By Numbers NFT", "DBNFT") {
transferOwnership(owner);
_baseExternalURI = baseExternalURI;
_contractMode = ContractMode.AllowlistOnly;
// first _open_ token id
_tokenIds._value = LAST_ALLOWLISTED_TOKEN_ID + 1;
// initial mint price
_mintPrice = 0;
// initial recipient
recipient = _recipient;
// set up the opensea proxy registry
_setOpenSeaRegistry(openSeaProxyRegistry);
}
/******************************************************************************************
* _____ ____ _ _ ______ _____ _____
* / ____/ __ \| \ | | ____|_ _/ ____|
* | | | | | | \| | |__ | || | __
* | | | | | | . ` | __| | || | |_ |
* | |___| |__| | |\ | | _| || |__| |
* \_____\____/|_| \_|_| |_____\_____|
*
* Functions for configuring / interacting with the contract itself
*/
/**
* @notice The current "mode" of the contract: either AllowlistOnly (0) or Open (1).
* In AllowlistOnly mode, a signed ticket is required to mint. In Open mode,
* minting is open to all.
*/
function getContractMode() public view returns (ContractMode) {
return _contractMode;
}
/**
* @notice Moves the contract mode to Open. Only the owner can call this. Once the
* contract moves to Open, it cannot be moved back to AllowlistOnly
*/
function openMinting() public onlyOwner {
_contractMode = ContractMode.Open;
}
/**
* @notice Returns the current cost to mint. Applies to either mode.
* (And of course, this does not include gas ⛽️)
*/
function getMintPrice() public view returns (uint256) {
return _mintPrice;
}
/**
* @notice Sets the cost to mint. Only the owner can call this.
*/
function setMintPrice(uint256 price) public onlyOwner {
_mintPrice = price;
}
/**
* @notice Sets the recipient. Cannot be called after the recipient is locked.
* Only the owner can call this.
*/
function setRecipient(address payable to) public onlyOwner {
require(!recipientLocked, "RECIPIENT_LOCKED");
recipient = to;
}
/**
* @notice Prevents any future changes to the recipient.
* Only the owner can call this.
* @dev This enables post-deploy configurability of the recipient,
* combined with the ability to lock it in to facilitate
* confidence as to where the funds will be able to go.
*/
function lockRecipient() public onlyOwner {
recipientLocked = true;
}
/**
* @notice Disburses the contract balance to the stored recipient.
* Only the owner can call this.
*/
function disburse() public onlyOwner {
recipient.transfer(address(this).balance);
}
/******************************************************************************************
* __ __ _____ _ _ _______ _____ _ _ _____
* | \/ |_ _| \ | |__ __|_ _| \ | |/ ____|
* | \ / | | | | \| | | | | | | \| | | __
* | |\/| | | | | . ` | | | | | | . ` | | |_ |
* | | | |_| |_| |\ | | | _| |_| |\ | |__| |
* |_| |_|_____|_| \_| |_| |_____|_| \_|\_____|
*
* Functions for minting tokens!
*/
/**
* @notice Mints a token by deploying the given drawing bytecode
* @param bytecode The bytecode of the drawing to mint a token for.
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
*
* Requires passed value of at least the current mint price.
* Will revert if there are no more tokens available or if the current contract
* mode is not yet Open.
*/
function mint(bytes memory bytecode) public payable {
require(_contractMode == ContractMode.Open, "NOT_OPEN");
uint256 tokenId = _tokenIds.current();
require(tokenId <= LAST_TOKEN_ID, 'SOLD_OUT');
_tokenIds.increment();
_mintAtTokenId(bytecode, tokenId);
}
/**
* @notice Mints a token at the specific token ID by deploying the given drawing bytecode.
* Requires passing a ticket id and a signature generated by the contract owner
* granting permission for the caller to mint the specific token ID.
* @param bytecode The bytecode of the drawing to mint a token for
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
* @param tokenId The token ID to mint. Needs to be in the range [0, LAST_ALLOWLISTED_TOKEN_ID]
* @param ticketId The ID of the ticket; included as part of the signed data
* @param signature The bytes of the signature that must have been generated
* by the current owner of the contract.
*
* Requires passed value of at least the current mint price.
*/
function mintTokenId(
bytes memory bytecode,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public payable onlyWithTicketFor(tokenId, ticketId, signature) {
require(tokenId <= LAST_ALLOWLISTED_TOKEN_ID, 'WRONG_TOKENID_RANGE');
_mintAtTokenId(bytecode, tokenId);
}
/**
* @dev Internal function that does the actual minting for both open and allowlisted mint
* @param bytecode The bytecode of the drawing to mint a token for
* @param tokenId The token ID to mint
*/
function _mintAtTokenId(
bytes memory bytecode,
uint256 tokenId
) internal {
require(msg.value >= _mintPrice, "WRONG_PRICE");
// Deploy the drawing
address addr = Drawing.deploy(bytecode, tokenId);
// Link the token ID to the drawing address
_drawingAddressForTokenId[tokenId] = addr;
// Mint the token (to the sender)
_safeMint(msg.sender, tokenId);
emit DrawingDeployed(tokenId, addr);
}
/**
* @notice Allows gas-less trading on OpenSea by safelisting the ProxyRegistry of the user
* @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
* @inheritdoc ERC721
*/
function isApprovedForAll(
address owner,
address operator
) public view override returns (bool) {
return super.isApprovedForAll(owner, operator) || _isOwnersOpenSeaProxy(owner, operator);
}
/******************************************************************************************
* _______ ____ _ ________ _ _ _____ ______ _____ ______ _____ _____
* |__ __/ __ \| |/ / ____| \ | | | __ \| ____| /\ | __ \| ____| __ \ / ____|
* | | | | | | ' /| |__ | \| | | |__) | |__ / \ | | | | |__ | |__) | (___
* | | | | | | < | __| | . ` | | _ /| __| / /\ \ | | | | __| | _ / \___ \
* | | | |__| | . \| |____| |\ | | | \ \| |____ / ____ \| |__| | |____| | \ \ ____) |
* |_| \____/|_|\_\______|_| \_| |_| \_\______/_/ \_\_____/|______|_| \_\_____/
*
* Functions for reading / querying tokens
*/
/**
* @dev Helper that gets the address for a given token and reverts if it is not present
* @param tokenId the token to get the address of
*/
function _addressForToken(uint256 tokenId) internal view returns (address) {
address addr = _drawingAddressForTokenId[tokenId];
require(addr != address(0), "UNKNOWN_ID");
return addr;
}
/**
* @dev Helper that pulls together the metadata struct for a given token
* @param tokenId the token to get the metadata for
* @param addr the address of its drawing contract
*/
function _getMetadata(uint256 tokenId, address addr) internal view returns (Token.Metadata memory) {
string memory tokenIdAsString = tokenId.toString();
return Token.Metadata(
string(abi.encodePacked("DBNFT #", tokenIdAsString)),
string(Drawing.description(addr)),
string(abi.encodePacked(_baseExternalURI, tokenIdAsString)),
uint256(uint160(addr)).toHexString()
);
}
/**
* @notice The ERC721 tokenURI of the given token as an application/json data URI
* @param tokenId the token to get the tokenURI of
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
address addr = _addressForToken(tokenId);
(, bytes memory bitmapData) = Drawing.render(addr);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.tokenURI(bitmapData, metadata);
}
/**
* @notice Returns the metadata of the token, without the image data, as a JSON string
* @param tokenId the token to get the metadata of
*/
function tokenMetadata(uint256 tokenId) public view returns (string memory) {
address addr = _addressForToken(tokenId);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.metadataAsJSON(metadata);
}
/**
* @notice Returns the underlying bytecode of the drawing contract
* @param tokenId the token to get the drawing bytecode of
*/
function tokenCode(uint256 tokenId) public view returns (bytes memory) {
address addr = _addressForToken(tokenId);
return addr.code;
}
/**
* @notice Renders the token and returns an estimate of the gas used and the bitmap data itself
* @param tokenId the token to render
*/
function renderToken(uint256 tokenId) public view returns (uint256, bytes memory) {
address addr = _addressForToken(tokenId);
return Drawing.render(addr);
}
/**
* @notice Returns a list of which tokens in the [0, LAST_ALLOWLISTED_TOKEN_ID]
* have already been minted.
*/
function mintedAllowlistedTokens() public view returns (uint256[] memory) {
uint8 count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
count++;
}
}
uint256[] memory result = new uint256[](count);
count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
result[count] = i;
count++;
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev Modified copy of OpenZeppelin ERC721 Enumerable.
*
* Changes:
* - gets rid of _removeTokenFromAllTokensEnumeration: no burns (saves space)
* - adds public accessor for the allTokens array
*/
abstract contract DBNERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "OWNER_INDEX_OOB");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < DBNERC721Enumerable.totalSupply(), "GLOBAL_INDEX_OOB");
return _allTokens[index];
}
/**
* @notice Get a list of all minted tokens.
* @dev No guarantee of order.
*/
function allTokens() public view returns (uint256[] memory) {
return _allTokens;
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// Based off of https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/
/// - but removes the _contractURI bits
/// - and makes it abstract
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's
/// gas-less trading and contractURI support
abstract contract OpenSeaTradable {
address private _proxyRegistry;
/// @notice Returns the current OS proxyRegistry address registered
function openSeaProxyRegistry() public view returns (address) {
return _proxyRegistry;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator
/// for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function _isOwnersOpenSeaProxy(address owner, address operator) internal virtual view
returns (bool)
{
address proxyRegistry_ = _proxyRegistry;
// if we have a proxy registry
if (proxyRegistry_ != address(0)) {
address ownerProxy = ProxyRegistry(proxyRegistry_).proxies(owner);
return ownerProxy == operator;
}
return false;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal virtual {
_proxyRegistry = proxyRegistryAddress;
}
}
contract ProxyRegistry {
mapping(address => address) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @dev Implements a mixin that uses ECDSA cryptography to restrict token minting to "ticket"-holders.
* This allows off-chain, gasless allowlisting of minting.
*
* A "Ticket" is a logical tuple of:
* - the Token ID
* - the address of a minter
* - the address of the token contract
* - a ticket ID (random number)
*
* By signing this tuple, the owner of the contract can grant permission to a specific address
* to mint a specific token ID at that specific token contract.
*/
abstract contract OwnerSignedTicketRestrictable is Ownable {
// Mapping to enable (very basic) ticket revocation
mapping (uint256 => bool) private _revokedTickets;
/**
* @dev Throws if the given signature, signed by the contract owner, does not grant
* the transaction sender a ticket to mint the given tokenId
* @param tokenId the ID of the token to check
* @param ticketId the ID of the ticket (included in signature)
* @param signature the bytes of the signature to use for verification
*
* This delegates straight into the checkTicket public function.
*/
modifier onlyWithTicketFor(uint256 tokenId, uint256 ticketId, bytes memory signature) {
checkTicket(msg.sender, tokenId, ticketId, signature);
_;
}
/**
* @notice Check the validity of a signature
* @dev Throws if the given signature wasn't signed by the contract owner for the
* "ticket" described by address(this) and the passed parameters
* (or if the ticket ID is revoked)
* @param minter the address of the minter in the ticket
* @param tokenId the token ID of the ticket
* @param ticketId the ticket ID
* @param signature the bytes of the signature
*
* Reuse of a ticket is prevented by existing controls preventing double-minting.
*/
function checkTicket(
address minter,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public view {
bytes memory params = abi.encode(
address(this),
minter,
tokenId,
ticketId
);
address addr = ECDSA.recover(
ECDSA.toEthSignedMessageHash(keccak256(params)),
signature
);
require(addr == owner(), "BAD_SIGNATURE");
require(!_revokedTickets[ticketId], "TICKET_REVOKED");
}
/**
* @notice Revokes the given ticket IDs, preventing them from being used in the future
* @param ticketIds the ticket IDs to revoke
* @dev This can do nothing if the ticket ID has already been used, but
* this function gives an escape hatch for accidents, etc.
*/
function revokeTickets(uint256[] calldata ticketIds) public onlyOwner {
for (uint i=0; i<ticketIds.length; i++) {
_revokedTickets[ticketIds[i]] = true;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./BitmapHeader.sol";
/**
* @dev Internal helper library to encapsulate interactions with a "Drawing" contract
*/
library Drawing {
/**
* @dev Deploys the given bytecode as a drawing contract
* @param bytecode The bytecode to pass to the CREATE opcode
* Must have been generated by the DBN compiler for predictable results.
* @param tokenId The tokenId to inject into the bytecode
* @return the address of the newly created contract
*
* Will also inject the given tokenID into the bytecode before deploy so that
* It is available in the deployed contract's context via a codecopy.
*
* The bytecode passed needs to be _deploy_ bytecode (so end up returning the
* actual bytecode). If any issues occur with the CREATE the transaction
* will fail with an assert (consuming all remaining gas). Detailed reasoning inline.
*/
function deploy(bytes memory bytecode, uint256 tokenId) internal returns (address) {
// First, inject the token id into the bytecode.
// The end of the bytecode is [2 bytes token id][32 bytes ipfs hash]
// (and we get the tokenID in in bigendian)
// This clearly assumes some coordination with the compiler (leaving this space blank!)
bytecode[bytecode.length - 32 - 2] = bytes1(uint8((tokenId & 0xFF00) >> 8));
bytecode[bytecode.length - 32 - 1] = bytes1(uint8(tokenId & 0xFF));
address addr;
assembly {
addr := create(0, add(bytecode, 0x20), mload(bytecode))
}
/*
if addr is zero, a few things could have happened:
a) out-of-gas in the create (which gets forwarded [current*(63/64) - 32000])
b) other exceptional halt (call stack too deep, invalid jump, etc)
c) revert from the create
in a): we should drain all existing gas and effectively bubble up the out of gas.
this makes sure that gas estimators do the right thing
in b): this is a nasty situation, so let's just drain away our gas anyway (true assert)
in c): pretty much same as b) — this is a bug in the passed bytecode, and we should fail.
that said, we _could_ check the μo return buffer for REVERT data, but no need for now.
So no matter what, we want to "assert" the addr is not zero
*/
assert(addr != address(0));
return addr;
}
/**
* @dev Renders the specified drawing contract as a bitmap
* @param addr The address of the drawing contract
* @return an estimation of the gas used and the 10962 bytes of the bitmap
*
* It calls the "0xBD" opcode of the drawing to get just the bitmap pixel data;
* the bitmap header is generated within this calling contract. This is to ensure
* that even if the deployed drawing doesn't conform to the DBN-drawing spec,
* a valid bitmap will always be returned.
*
* To further ensure that a valid bitmap is always returned, if the call
* to the drawing contract reverts, a bitmap will still be returned
* (though with the center pixel set to "55" to facilitate debugging)
*/
function render(address addr) internal view returns (uint256, bytes memory) {
uint bitmapLength = 10962;
uint headerLength = 40 + 14 + 404;
uint pixelDataLength = (10962 - headerLength);
bytes memory result = new bytes(bitmapLength);
bytes memory input = hex"BD";
uint256 startGas = gasleft();
BitmapHeader.writeTo(result);
uint resultOffset = 0x20 + headerLength; // after the header (and 0x20 for the dynamic byte length)
assembly {
let success := staticcall(
gas(),
addr,
add(input, 0x20),
1,
0, // return dst, but we're using the returnbuffer
0 // return length (we're using the returnbuffer)
)
let dataDst := add(result, resultOffset)
switch success
case 1 {
// Render call succeeded!
// copy min(returndataize, pixelDataLength) from the returnbuffer
// in happy path: returndatasize === pixeldatalength
// -> then great, either
// unexpected (too little data): returndatasize < pixeldatalength
// -> then we mustn't copy too much from the buffer! (use returndatasize)
// unexpected (too much data): returndatasize > pixeldatalength
// -> then we mustn't overflow our result! (use pixeldatalength)
let copySize := returndatasize()
if gt(copySize, pixelDataLength) {
copySize := pixelDataLength
}
returndatacopy(
dataDst, // dst offset
0, // src offset
copySize // length
)
}
case 0 {
// Render call failed :/
// Leave a little indicating pixel to hopefully help debugging
mstore8(
add(dataDst, 5250), // location of the center pixel (50 * 104 + 50)
0x55
)
}
}
// this overestimates _some_, but that's fine
uint256 endGas = gasleft();
return ((startGas - endGas), result);
}
/**
* @dev Gets the description stored in the code of a drawing contract
* @param addr The address of the drawing contract
* @return a (possibly empty) string description of the drawing
*
* It calls the "0xDE" opcode of the drawing to get its description.
* If the call fails, it will return an empty string.
*/
function description(address addr) internal view returns (string memory) {
(bool success, bytes memory desc) = addr.staticcall(hex"DE");
if (success) {
return string(desc);
} else {
return "";
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Namespace to encapsulate a "Metadata" struct for a drawing
*/
library Token {
struct Metadata {
string name;
string description;
string externalUrl;
string drawingAddress;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Token.sol";
import "./Base64.sol";
/**
* @dev Internal library encapsulating JSON / Token URI serialization
*/
library Serialize {
/**
* @dev Generates a ERC721 TokenURI for the given data
* @param bitmapData The raw bytes of the drawing's bitmap
* @param metadata The struct holding information about the drawing
* @return a string application/json data URI containing the token information
*
* We do _not_ base64 encode the JSON. This results in a slightly non-compliant
* data URI, because of the commas (and potential non-URL-safe characters).
* Empirically, this is fine: and re-base64-encoding everything would use
* gas and time and is not worth it.
*
* There's also a few ways we could encode the image in the metadata JSON:
* 1. image/bmp data url in the `image` field (base64-encoded given binary data)
* 2. raw svg data in the `image_data` field
* 3. image/svg data url in the `image` field (containing a base64-encoded image, but not itself base64-encoded)
* 4. (3), but with another layer of base64 encoding
* Through some trial and error, (1) does not work with Rarible or OpenSea. The rest do. (4) would be yet another
* layer of base64 (taking time, so is not desirable), (2) uses a potentially non-standard field, so we use (3).
*/
function tokenURI(bytes memory bitmapData, Token.Metadata memory metadata) internal pure returns (string memory) {
string memory imageKey = "image";
bytes memory imageData = _svgDataURI(bitmapData);
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
'data:application/json,',
fragment,
// image data :)
'","', imageKey, '":"', imageData, '"}'
));
}
/**
* @dev Returns just the metadata of the image (no bitmap data) as a JSON string
* @param metadata The struct holding information about the drawing
*/
function metadataAsJSON(Token.Metadata memory metadata) internal pure returns (string memory) {
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
fragment,
'"}'
));
}
/**
* @dev Returns a partial JSON string with the metadata of the image.
* Used by both the full tokenURI and the plain-metadata serializers.
* @param metadata The struct holding information about the drawing
*/
function _metadataJSONFragmentWithoutImage(Token.Metadata memory metadata) internal pure returns (string memory) {
return string(abi.encodePacked(
// name
'{"name":"',
metadata.name,
// description
'","description":"',
metadata.description,
// external_url
'","external_url":"',
metadata.externalUrl,
// code address
'","drawing_address":"',
metadata.drawingAddress
));
}
/**
* @dev Generates a data URI of an SVG containing an <image> tag containing the given bitmapData
* @param bitmapData The raw bytes of the drawing's bitmap
*/
function _svgDataURI(bytes memory bitmapData) internal pure returns (bytes memory) {
return abi.encodePacked(
"data:image/svg+xml,",
"<svg xmlns='http://www.w3.org/2000/svg' width='303' height='303'><image width='303' height='303' style='image-rendering: pixelated' href='",
"data:image/bmp;base64,",
Base64.encode(bitmapData),
"'/></svg>"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library encapsulating logic to generate the header + palette for a bitmap.
*
* Uses the "40-byte" header format, as described at
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* Note that certain details (width, height, palette size, file size) are hardcoded
* based off the DBN-specific assumptions of 101x101 with 101 shades of grey.
*
*/
library BitmapHeader {
bytes32 internal constant HEADER1 = 0x424dd22a000000000000ca010000280000006500000065000000010008000000;
bytes22 internal constant HEADER2 = 0x00000000000000000000000000006500000000000000;
/**
* @dev Writes a 458 byte bitmap header + palette to the given array
* @param output The destination array. Gets mutated!
*/
function writeTo(bytes memory output) internal pure {
assembly {
mstore(add(output, 0x20), HEADER1)
mstore(add(output, 0x40), HEADER2)
}
// palette index is "DBN" color : [0, 100]
// map that to [0, 255] via:
// 255 - ((255 * c) / 100)
for (uint i = 0; i < 101; i++) {
bytes1 c = bytes1(uint8(255 - ((255 * i) / 100)));
uint o = i*4 + 54; // after the header
output[o] = c;
output[o + 1] = c;
output[o + 2] = c;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper library for base64-encoding bytes
*/
library Base64 {
uint256 internal constant ALPHA1 = 0x4142434445464748494a4b4c4d4e4f505152535455565758595a616263646566;
uint256 internal constant ALPHA2 = 0x6768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f;
/**
* @dev Encodes the given bytearray to base64
* @param input The input data
* @return the output data
*/
function encode(bytes memory input) internal pure returns (bytes memory) {
if (input.length == 0) {
return input;
}
bytes memory output = new bytes(_encodedLength(input.length));
uint remaining = input.length;
assembly {
let src := add(input, 0x20)
let dst := add(output, 0x20)
// chunk loop
for {} gt(remaining, 0) {} {
let chunk := shr(16, mload(src))
let processing := 30
let sixtetCounter := 240 // 30 * 8
if lt(remaining, 30) {
processing := remaining
// slide right by 30–#remaining bytes (shl by 3 to get bits)
chunk := shr(shl(3, sub(30, remaining)), chunk)
// but now it needs to be nudge to the left by a few bits,
// to make sure total number of bits is multiple of 6
// 0 mod 3: nudge 0 bits
// 1 mod 3: nudge 4 bits
// 2 mod 3: nudge 2 bits
// we take advantage that this is the same as
// (v * 4) % 6
// this is empirically true, though I don't remember the number theory proving it
let nudgeBits := mulmod(remaining, 4, 6)
chunk := shl(nudgeBits, chunk)
// initial sixtet (remaining * 8 + nudge)
sixtetCounter := add(shl(3, remaining), nudgeBits)
}
remaining := sub(remaining, processing)
src := add(src, processing)
// byte loop
for {} gt(sixtetCounter, 0) {} {
sixtetCounter := sub(sixtetCounter, 6)
let val := shr(sixtetCounter, and(shl(sixtetCounter, 0x3F), chunk))
let alpha := ALPHA1
if gt(val, 0x1F) {
alpha := ALPHA2
val := sub(val, 0x20)
}
let char := byte(val, alpha)
mstore8(dst, char)
dst := add(dst, 1)
}
}
// padding depending on input length % 3
switch mod(mload(input), 3)
case 1 {
// two pads
mstore8(dst, 0x3D) // 0x3d is =
mstore8(add(1, dst), 0x3D) // 0x3d is =
}
case 2 {
// one pad
mstore8(dst, 0x3D)
}
}
return output;
}
/**
* @dev Helper to get the length of the output data
*
* Implements Ceil(inputLength / 3) * 4
*/
function _encodedLength(uint inputLength) internal pure returns (uint) {
return ((inputLength + 2) / 3) * 4;
}
}
|
Disburses the contract balance to the stored recipient. Only the owner can call this./
|
function disburse() public onlyOwner {
recipient.transfer(address(this).balance);
}
| 13,463,210
|
//*********************************************************************//
//*********************************************************************//
// __ __ __ __ _ __
// / / / /___ _/ /_ ___ _____/ /_ ____ _ ____ _(_)____/ /____
// / /_/ / __ `/ __ \/ _ \/ ___/ __ \/ __ `/ / __ `/ / ___/ / ___/
// / __ / /_/ / /_/ / __(__ ) / / / /_/ / / /_/ / / / / (__ )
// /_/ /_/\__,_/_.___/\___/____/_/ /_/\__,_/ \__, /_/_/ /_/____/
// /____/
//
// A series of digital art that shows a different heritage in Ethiopian in traditional costumes and hairstyles,
// HG is a collection of 1000 Habesha Girls NFTs unique digital collectibles living on the Ethereum blockchain.
//
//*********************************************************************//
//*********************************************************************//
//-------------DEPENDENCIES--------------------------//
// File: ./contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.9;
// 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 subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: ./contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [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: ./contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: ./contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @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: ./contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
// File: ./contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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`.
*
* 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;
/**
* @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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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);
}
// File: ./contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: ./contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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);
}
// File: ./contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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: ./contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract 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: ./contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: ./contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.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 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 mintedTokenNumbers = 0;
uint256 public immutable collectionSize;
// 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 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
_name = name_;
_symbol = symbol_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
/**
* Returns the total amount of tokens minted in the contract.
*/
function totalSupply() public view override returns (uint256) {
return mintedTokenNumbers;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < collectionSize, "ERC721A: global index out of bounds");
if (_ownerships[index].addr != address(0)) {
return index;
}
revert("ERC721A: Token not minted");
}
/**
* @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(_addressData[owner].balance > 0, "ERC721A: owner index out of bounds");
TokenOwnership memory ownership = _ownerships[index];
if (ownership.addr == owner) {
return index;
}
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)
{
TokenOwnership memory ownership = _ownerships[tokenId];
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: The given address is not the 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 _ownerships[tokenId].addr != address(0);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
*
* 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(tokenId > 1, "ERC721: can't mint token id 1 and 0");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfers(address(0), to, tokenId);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + 1,
addressData.numberMinted + 1
);
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
emit Transfer(address(0), to, tokenId);
mintedTokenNumbers = mintedTokenNumbers + 1;
_afterTokenTransfers(address(0), to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @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);
// 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));
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId);
}
/**
* @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);
}
/**
* @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 any token transfer. This includes minting
*
* 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 _beforeTokenTransfers(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting.
*
* 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 _afterTokenTransfers(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
abstract contract AknetAble {
address public AKNETADDRESS = 0x0E1b37113B68202FB8e3437Aa113dcf035afBDb1;
modifier isAKNET() {
require(msg.sender == AKNETADDRESS, "Ownable: caller is not AKNET");
_;
}
}
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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
}
abstract contract Withdrawable is Ownable, AknetAble {
address public ArtistADDRESS = 0x12620ABBa9435e21A6a9a6fAE8be66E3ba01f3c2;
address[] public payableAddresses = [AKNETADDRESS, 0xDc5DAa30A65e882Aeb2b23c6c54c5A4F81f94D9a, ArtistADDRESS];
uint256[] public payableFees = [9,9,82];
uint256 public payableAddressCount = 3;
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllAknet() public isAKNET {
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);
}
}
}
abstract contract AknetERC721A is
Ownable,
ERC721A,
Withdrawable,
ReentrancyGuard {
constructor(
string memory tokenName,
string memory tokenSymbol
) ERC721A(tokenName, tokenSymbol, 1000 ) {}
using SafeMath for uint256;
uint8 public CONTRACT_VERSION = 1;
string public _baseTokenURI = "ipfs://QmdWuZ4VCngnkmSpAUeXcxm8ryFvF1Yz5jtaDMTGXbV5zA/";
bool public mintingOpen = true;
uint256 public mintingFee = 0.1 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, uint256 tokenId) public onlyOwner {
require(tokenId <= collectionSize, "Cannot mint over supply cap");
_mint(_to, tokenId);
}
/////////////// 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 mintNft(address _to, uint256 tokenId) public payable {
require(tokenId <= collectionSize, "Cannot mint over supply cap");
require(mintingOpen == true, "Minting is not open right now!");
require(msg.value >= mintingFee, "Value needs to be equal or higher the mint fee!");
_mint(_to, tokenId);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
function updateMintingFee(uint256 _feeInWei) public onlyOwner {
mintingFee = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return mintingFee.mul(_count);
}
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/HabeshaGirlsContract.sol
//SPDX-License-Identifier: MIT
contract HabeshaGirlsContract is AknetERC721A {
constructor() AknetERC721A("Habesha Girls", "HG"){}
function contractURI() public pure returns (string memory) {
return "https://gateway.pinata.cloud/ipfs/QmfXkZsYJiUruYFXC8La9thr3NJq7TLrjBySV6ujCtFKus";
}
}
//*********************************************************************//
//*********************************************************************//
//
//
// AAA KKKKKKKKK KKKKKKKNNNNNNNN NNNNNNNN EEEEEEEEEEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTT
// A:::A K:::::::K K:::::KN:::::::N N::::::N E::::::::::::::::::::ET:::::::::::::::::::::T
// A:::::A K:::::::K K:::::KN::::::::N N::::::N E::::::::::::::::::::ET:::::::::::::::::::::T
// A:::::::A K:::::::K K::::::KN:::::::::N N::::::N EE::::::EEEEEEEEE::::ET:::::TT:::::::TT:::::T
// A:::::::::A KK::::::K K:::::KKKN::::::::::N N::::::N E:::::E EEEEEETTTTTT T:::::T TTTTTT
// A:::::A:::::A K:::::K K:::::K N:::::::::::N N::::::N E:::::E T:::::T
// A:::::A A:::::A K::::::K:::::K N:::::::N::::N N::::::N E::::::EEEEEEEEEE T:::::T
// A:::::A A:::::A K:::::::::::K N::::::N N::::N N::::::N E:::::::::::::::E T:::::T
// A:::::A A:::::A K:::::::::::K N::::::N N::::N:::::::N E:::::::::::::::E T:::::T
// A:::::AAAAAAAAA:::::A K::::::K:::::K N::::::N N:::::::::::N E::::::EEEEEEEEEE T:::::T
// A:::::::::::::::::::::A K:::::K K:::::K N::::::N N::::::::::N E:::::E T:::::T
// A:::::AAAAAAAAAAAAA:::::A KK::::::K K:::::KKKN::::::N N:::::::::N E:::::E EEEEEE T:::::T
// A:::::A A:::::A K:::::::K K::::::KN::::::N N::::::::N EE::::::EEEEEEEE:::::E TT:::::::TT
// A:::::A A:::::A K:::::::K K:::::KN::::::N N:::::::N ...... E::::::::::::::::::::E T:::::::::T
// A:::::A A:::::A K:::::::K K:::::KN::::::N N::::::N .::::. E::::::::::::::::::::E T:::::::::T
// AAAAAAA AAAAAAAKKKKKKKKK KKKKKKKNNNNNNNN NNNNNNN ...... EEEEEEEEEEEEEEEEEEEEEE TTTTTTTTTTT
//
//
// V1.0.0
//
// Habesha girls Nft smart contract was created
// with partnership with Akn.et
// Aknet allows you to launch large scale
// NFT projects!
//
//*********************************************************************//
//*********************************************************************//
|
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);
}
| 9,892,606
|
./full_match/11155111/0xF35e2d373E60B443b521D4A3da23aA3a5F207630/sources/contracts/Artify.sol
|
------------------------------------NEED TO MAKE IT RIGHT ----------------------------------------------------------------------------------------- if applied from buyer/
|
function initiateDelivery(uint256 _artworkId) external onlySupplier {
require(artworkExists(_artworkId), "Artwork does not exist");
require(artworks[_artworkId].currentOwner == msg.sender, "Only Owner Can initiate Delivery");
artworks[_artworkId].isDelivered = true;
}
| 3,828,638
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/IStakingRewards.sol";
import "./RewardsDistributionRecipient.sol";
contract StakingRewards is
IStakingRewards,
RewardsDistributionRecipient,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 30 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public unallocatedReward = 0;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/* ========== CONSTRUCTOR ========== */
constructor(
address _rewardsDistribution,
address _rewardsToken,
address _stakingToken
) public {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
rewardsDistribution = _rewardsDistribution;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function getReward(address beneficiary) internal {
uint256 reward = rewards[beneficiary];
if (reward > 0) {
rewards[beneficiary] = 0;
rewardsToken.safeTransfer(beneficiary, reward);
}
}
function stake(uint256 amount)
external
nonReentrant
updateReward(msg.sender)
{
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
getReward(msg.sender);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
getReward(msg.sender);
emit Withdrawn(msg.sender, amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public nonReentrant {
uint256 amount = _balances[msg.sender];
stakingToken.safeTransfer(msg.sender, amount);
emit EmergencyWithdraw(msg.sender, amount);
rewards[msg.sender] = 0;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(uint256 reward, uint256 duration)
external
onlyRewardsDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardsDuration = duration;
rewardRate = reward.add(unallocatedReward).div(rewardsDuration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardsDuration = duration;
rewardRate = reward.add(unallocatedReward).add(leftover).div(rewardsDuration);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(
rewardRate <= balance.div(rewardsDuration),
"Provided reward too high"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
unallocatedReward = 0;
emit RewardAdded(reward);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
if (_totalSupply == 0 && unallocatedReward == 0) {
uint256 pastTime = Math.min(block.timestamp, periodFinish).sub(lastUpdateTime);
unallocatedReward = pastTime.mul(rewardRate);
}
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
}
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw() public nonReentrant {
uint256 amount = _balances[msg.sender];
stakingToken.safeTransfer(msg.sender, amount);
emit EmergencyWithdraw(msg.sender, amount);
rewards[msg.sender] = 0;
}
| 14,069,746
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
// This is only kept for backward compatability / upgrading
import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol";
import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol";
import {IRegistrar} from "../interfaces/IRegistrar.sol";
import {StorageSlot} from "../oz/utils/StorageSlot.sol";
import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol";
import {IZNSHub} from "../interfaces/IZNSHub.sol";
contract Registrar is
IRegistrar,
OwnableUpgradeable,
ERC721PausableUpgradeable
{
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
// Data recorded for each domain
struct DomainRecord {
address minter;
bool metadataLocked;
address metadataLockedBy;
address controller;
uint256 royaltyAmount;
uint256 parentId;
address subdomainContract;
}
// A map of addresses that are authorised to register domains.
mapping(address => bool) public controllers;
// A mapping of domain id's to domain data
// This essentially expands the internal ERC721's token storage to additional fields
mapping(uint256 => DomainRecord) public records;
/**
* @dev Storage slot with the admin of the contract.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
// The beacon address
address public beacon;
// If this is a subdomain contract these will be set
uint256 public rootDomainId;
address public parentRegistrar;
// The event emitter
IZNSHub public zNSHub;
uint8 private test; // ignore
uint256 private gap; // ignore
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
modifier onlyController() {
if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) {
revert("ZR: Not controller");
}
_;
}
modifier onlyOwnerOf(uint256 id) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
_;
}
function initialize(
address parentRegistrar_,
uint256 rootDomainId_,
string calldata collectionName,
string calldata collectionSymbol,
address zNSHub_
) public initializer {
// __Ownable_init(); // Purposely not initializing ownable since we override owner()
if (parentRegistrar_ == address(0)) {
// create the root domain
_createDomain(0, 0, msg.sender, address(0));
} else {
rootDomainId = rootDomainId_;
parentRegistrar = parentRegistrar_;
}
zNSHub = IZNSHub(zNSHub_);
__ERC721Pausable_init();
__ERC721_init(collectionName, collectionSymbol);
}
// Used to upgrade existing registrar to new registrar
function upgradeFromNormalRegistrar(address zNSHub_) public {
require(msg.sender == _getAdmin(), "Not Proxy Admin");
zNSHub = IZNSHub(zNSHub_);
}
function owner() public view override returns (address) {
return zNSHub.owner();
}
/*
* External Methods
*/
/**
* @notice Authorizes a controller to control the registrar
* @param controller The address of the controller
*/
function addController(address controller) external {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(!controllers[controller], "ZR: Controller is already added");
controllers[controller] = true;
emit ControllerAdded(controller);
}
/**
* @notice Unauthorizes a controller to control the registrar
* @param controller The address of the controller
*/
function removeController(address controller) external override onlyOwner {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(controllers[controller], "ZR: Controller does not exist");
controllers[controller] = false;
emit ControllerRemoved(controller);
}
/**
* @notice Pauses the registrar. Can only be done when not paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the registrar. Can only be done when not paused.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Registers a new (sub) domain
* @param parentId The parent domain
* @param label The label of the domain
* @param minter the minter of the new domain
* @param metadataUri The uri of the metadata
* @param royaltyAmount The amount of royalty this domain pays
* @param locked Whether the domain is locked or not
*/
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external override onlyController returns (uint256) {
return
_registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
}
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external override onlyController returns (uint256) {
// Register the domain
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// immediately send domain to user
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external onlyController returns (uint256) {
// Register domain, `minter` is the minter
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// Create subdomain contract as a beacon proxy
address subdomainContract = address(
new BeaconProxy(zNSHub.registrarBeacon(), "")
);
// More maintainable instead of using `data` in constructor
Registrar(subdomainContract).initialize(
address(this),
id,
"Zer0 Name Service",
"ZNS",
address(zNSHub)
);
// Indicate that the subdomain has a contract
records[id].subdomainContract = subdomainContract;
zNSHub.addRegistrar(id, subdomainContract);
// immediately send the domain to the user (from the minter)
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function _registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) internal returns (uint256) {
require(bytes(label).length > 0, "ZR: Empty name");
// subdomain cannot be minted on domains which are subdomain contracts
require(
records[parentId].subdomainContract == address(0),
"ZR: Parent is subcontract"
);
if (parentId != rootDomainId) {
// Domain parents must exist
require(_exists(parentId), "ZR: No parent");
}
// Create the child domain under the parent domain
uint256 labelHash = uint256(keccak256(bytes(label)));
address controller = msg.sender;
// Calculate the new domain's id and create it
uint256 domainId = uint256(
keccak256(abi.encodePacked(parentId, labelHash))
);
_createDomain(parentId, domainId, minter, controller);
_setTokenURI(domainId, metadataUri);
if (locked) {
records[domainId].metadataLockedBy = minter;
records[domainId].metadataLocked = true;
}
if (royaltyAmount > 0) {
records[domainId].royaltyAmount = royaltyAmount;
}
zNSHub.domainCreated(
domainId,
label,
labelHash,
parentId,
minter,
controller,
metadataUri,
royaltyAmount
);
return domainId;
}
/**
* @notice Sets the domain royalty amount
* @param id The domain to set on
* @param amount The royalty amount
*/
function setDomainRoyaltyAmount(uint256 id, uint256 amount)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
records[id].royaltyAmount = amount;
zNSHub.royaltiesAmountChanged(id, amount);
}
/**
* @notice Both sets and locks domain metadata uri in a single call
* @param id The domain to lock
* @param uri The uri to set
*/
function setAndLockDomainMetadata(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
_setDomainLock(id, msg.sender, true);
}
/**
* @notice Sets the domain metadata uri
* @param id The domain to set on
* @param uri The uri to set
*/
function setDomainMetadataUri(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
}
/**
* @notice Locks a domains metadata uri
* @param id The domain to lock
* @param toLock whether the domain should be locked or not
*/
function lockDomainMetadata(uint256 id, bool toLock) external override {
_validateLockDomainMetadata(id, toLock);
_setDomainLock(id, msg.sender, toLock);
}
/*
* Public View
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override(ERC721Upgradeable, IERC721Upgradeable)
returns (address)
{
// Check if the token is in this contract
if (_tokenOwners.contains(tokenId)) {
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
return zNSHub.ownerOf(tokenId);
}
/**
* @notice Returns whether or not an account is a a controller registered on this contract
* @param account Address of account to check
*/
function isController(address account) external view override returns (bool) {
bool accountIsController = controllers[account];
return accountIsController;
}
/**
* @notice Returns whether or not a domain is exists
* @param id The domain
*/
function domainExists(uint256 id) public view override returns (bool) {
bool domainNftExists = _exists(id);
return domainNftExists;
}
/**
* @notice Returns the original minter of a domain
* @param id The domain
*/
function minterOf(uint256 id) public view override returns (address) {
address minter = records[id].minter;
return minter;
}
/**
* @notice Returns whether or not a domain's metadata is locked
* @param id The domain
*/
function isDomainMetadataLocked(uint256 id)
public
view
override
returns (bool)
{
bool isLocked = records[id].metadataLocked;
return isLocked;
}
/**
* @notice Returns who locked a domain's metadata
* @param id The domain
*/
function domainMetadataLockedBy(uint256 id)
public
view
override
returns (address)
{
address lockedBy = records[id].metadataLockedBy;
return lockedBy;
}
/**
* @notice Returns the controller which created the domain on behalf of a user
* @param id The domain
*/
function domainController(uint256 id) public view override returns (address) {
address controller = records[id].controller;
return controller;
}
/**
* @notice Returns the current royalty amount for a domain
* @param id The domain
*/
function domainRoyaltyAmount(uint256 id)
public
view
override
returns (uint256)
{
uint256 amount = records[id].royaltyAmount;
return amount;
}
/**
* @notice Returns the parent id of a domain.
* @param id The domain
*/
function parentOf(uint256 id) public view override returns (uint256) {
require(_exists(id), "ZR: Does not exist");
uint256 parentId = records[id].parentId;
return parentId;
}
/*
* Internal Methods
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._transfer(from, to, tokenId);
// Need to emit transfer events on event emitter
zNSHub.domainTransferred(from, to, tokenId);
}
function _setDomainMetadataUri(uint256 id, string memory uri) internal {
_setTokenURI(id, uri);
zNSHub.metadataChanged(id, uri);
}
function _validateLockDomainMetadata(uint256 id, bool toLock) internal view {
if (toLock) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
} else {
require(isDomainMetadataLocked(id), "ZR: Not locked");
require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker");
}
}
// internal - creates a domain
function _createDomain(
uint256 parentId,
uint256 domainId,
address minter,
address controller
) internal {
// Create the NFT and register the domain data
_mint(minter, domainId);
records[domainId] = DomainRecord({
parentId: parentId,
minter: minter,
metadataLocked: false,
metadataLockedBy: address(0),
controller: controller,
royaltyAmount: 0,
subdomainContract: address(0)
});
}
function _setDomainLock(
uint256 id,
address locker,
bool lockStatus
) internal {
records[id].metadataLockedBy = locker;
records[id].metadataLocked = lockStatus;
zNSHub.metadataLockChanged(id, locker, lockStatus);
}
function adminBurnToken(uint256 tokenId) external onlyOwner {
_burn(tokenId);
delete (records[tokenId]);
}
function adminTransfer(
address from,
address to,
uint256 tokenId
) external onlyOwner {
_transfer(from, to, tokenId);
}
function adminSetMetadataUri(uint256 id, string memory uri)
external
onlyOwner
{
_setDomainMetadataUri(id, uri);
}
function registerDomainAndSendBulk(
uint256 parentId,
uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset
uint256 startingIndex,
uint256 endingIndex,
address minter,
string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../
uint256 royaltyAmount,
bool locked
) external onlyController {
require(endingIndex - startingIndex > 0, "Invalid number of domains");
uint256 result;
for (uint256 i = startingIndex; i < endingIndex; i++) {
result = _registerDomain(
parentId,
uint2str(i + namingOffset),
minter,
string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))),
royaltyAmount,
locked
);
}
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ERC721Upgradeable.sol";
import "../../utils/PausableUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev ERC721 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 ERC721PausableUpgradeable is
Initializable,
ERC721Upgradeable,
PausableUpgradeable
{
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol";
import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol";
interface IRegistrar is
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
// Emitted when a controller is removed
event ControllerAdded(address indexed controller);
// Emitted whenever a controller is removed
event ControllerRemoved(address indexed controller);
// Emitted whenever a new domain is created
event DomainCreated(
uint256 indexed id,
string label,
uint256 indexed labelHash,
uint256 indexed parent,
address minter,
address controller,
string metadataUri,
uint256 royaltyAmount
);
// Emitted whenever the metadata of a domain is locked
event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked);
// Emitted whenever the metadata of a domain is changed
event MetadataChanged(uint256 indexed id, string uri);
// Emitted whenever the royalty amount is changed
event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount);
// Authorises a controller, who can register domains.
function addController(address controller) external;
// Revoke controller permission for an address.
function removeController(address controller) external;
// Registers a new sub domain
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external returns (uint256);
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
// Set a domains metadata uri and lock that domain from being modified
function setAndLockDomainMetadata(uint256 id, string memory uri) external;
// Lock a domain's metadata so that it cannot be changed
function lockDomainMetadata(uint256 id, bool toLock) external;
// Update a domain's metadata uri
function setDomainMetadataUri(uint256 id, string memory uri) external;
// Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places)
function setDomainRoyaltyAmount(uint256 id, uint256 amount) external;
// Returns whether an address is a controller
function isController(address account) external view returns (bool);
// Checks whether or not a domain exists
function domainExists(uint256 id) external view returns (bool);
// Returns the original minter of a domain
function minterOf(uint256 id) external view returns (address);
// Checks if a domains metadata is locked
function isDomainMetadataLocked(uint256 id) external view returns (bool);
// Returns the address which locked the domain metadata
function domainMetadataLockedBy(uint256 id) external view returns (address);
// Gets the controller that registered a domain
function domainController(uint256 id) external view returns (address);
// Gets a domains current royalty amount
function domainRoyaltyAmount(uint256 id) external view returns (uint256);
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot)
internal
pure
returns (AddressSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot)
internal
pure
returns (BooleanSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot)
internal
pure
returns (Bytes32Slot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot)
internal
pure
returns (Uint256Slot storage r)
{
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(
_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
);
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import {IRegistrar} from "./IRegistrar.sol";
interface IZNSHub {
function addRegistrar(uint256 rootDomainId, address registrar) external;
function isController(address controller) external returns (bool);
function getRegistrarForDomain(uint256 domainId)
external
view
returns (IRegistrar);
function ownerOf(uint256 domainId) external view returns (address);
function domainExists(uint256 domainId) external view returns (bool);
function owner() external view returns (address);
function registrarBeacon() external view returns (address);
function domainTransferred(
address from,
address to,
uint256 tokenId
) external;
function domainCreated(
uint256 id,
string calldata name,
uint256 nameHash,
uint256 parent,
address minter,
address controller,
string calldata metadataUri,
uint256 royaltyAmount
) external;
function metadataLockChanged(
uint256 id,
address locker,
bool isLocked
) external;
function metadataChanged(uint256 id, string calldata uri) external;
function royaltiesAmountChanged(uint256 id, uint256 amount) external;
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.9;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap internal _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_)
internal
initializer
{
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_)
internal
initializer
{
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721Upgradeable.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (
bytes32 slot
) {
require(
slot == _IMPLEMENTATION_SLOT,
"ERC1967Upgrade: unsupported proxiableUUID"
);
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// 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);
}
}
}
}
|
Storage slot with the address of the current implementation. This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is validated in the constructor./ Emitted when the implementation is upgraded./ Returns the current implementation address./
|
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
| 143,985
|
pragma solidity ^0.8.10;
import "./ERC721.sol";
import "./Ownable.sol";
import "./Strings.sol";
/// @notice Thrown when completing the transaction results in overallocation of Pixelmon.
error MintedOut();
/// @notice Thrown when the dutch auction phase has not yet started, or has already ended.
error AuctionNotStarted();
/// @notice Thrown when the user has already minted two Pixelmon in the dutch auction.
error MintingTooMany();
/// @notice Thrown when the value of the transaction is not enough for the current dutch auction or mintlist price.
error ValueTooLow();
/// @notice Thrown when the user is not on the mintlist.
error NotMintlisted();
/// @notice Thrown when the caller is not the EvolutionSerum contract, and is trying to evolve a Pixelmon.
error UnauthorizedEvolution();
/// @notice Thrown when an invalid evolution is given by the EvolutionSerum contract.
error UnknownEvolution();
// ______ __ __ __ ______ __ __ __ ______ __ __
// /\ == \ /\ \ /\_\_\_\ /\ ___\ /\ \ /\ "-./ \ /\ __ \ /\ "-.\ \
// \ \ _-/ \ \ \ \/_/\_\/_ \ \ __\ \ \ \____ \ \ \-./\ \ \ \ \/\ \ \ \ \-. \
// \ \_\ \ \_\ /\_\/\_\ \ \_____\ \ \_____\ \ \_\ \ \_\ \ \_____\ \ \_\\"\_\
// \/_/ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_/ \/_/ \/_____/ \/_/ \/_/
//
/// @title Generation 1 Pixelmon NFTs
/// @author delta devs (https://www.twitter.com/deltadevelopers)
contract Pixelmon is ERC721, Ownable {
using Strings for uint256;
/*///////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Determines the order of the species for each tokenId, mechanism for choosing starting index explained post mint, explanation hash: acb427e920bde46de95103f14b8e57798a603abcf87ff9d4163e5f61c6a56881.
uint constant public provenanceHash = 0x9912e067bd3802c3b007ce40b6c125160d2ccb5352d199e20c092fdc17af8057;
/// @dev Sole receiver of collected contract funds, and receiver of 330 Pixelmon in the constructor.
address constant gnosisSafeAddress = 0xF6BD9Fc094F7aB74a846E5d82a822540EE6c6971;
/// @dev 7750, plus 330 for the Pixelmon Gnosis Safe
uint constant auctionSupply = 7750 + 330;
/// @dev The offsets are the tokenIds that the corresponding evolution stage will begin minting at.
uint constant secondEvolutionOffset = 10005;
uint constant thirdEvolutionOffset = secondEvolutionOffset + 4013;
uint constant fourthEvolutionOffset = thirdEvolutionOffset + 1206;
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev The next tokenID to be minted for each of the evolution stages
uint secondEvolutionSupply = 0;
uint thirdEvolutionSupply = 0;
uint fourthEvolutionSupply = 0;
/// @notice The address of the contract permitted to mint evolved Pixelmon.
address public serumContract;
/// @notice Returns true if the user is on the mintlist, if they have not already minted.
mapping(address => bool) public mintlisted;
/*///////////////////////////////////////////////////////////////
AUCTION STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Starting price of the auction.
uint256 constant public auctionStartPrice = 3 ether;
/// @notice Unix Timestamp of the start of the auction.
/// @dev Monday, February 7th 2022, 13:00:00 converted to 1644256800 (GMT -5)
uint256 constant public auctionStartTime = 1644256800;
/// @notice Current mintlist price, which will be updated after the end of the auction phase.
/// @dev We started with signatures, then merkle tree, but landed on mapping to reduce USER gas fees.
uint256 public mintlistPrice = 0.75 ether;
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public baseURI;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploys the contract, minting 330 Pixelmon to the Gnosis Safe and setting the initial metadata URI.
constructor(string memory _baseURI) ERC721("Pixelmon", "PXLMN") {
baseURI = _baseURI;
unchecked {
balanceOf[gnosisSafeAddress] += 330;
totalSupply += 330;
for (uint256 i = 0; i < 330; i++) {
ownerOf[i] = gnosisSafeAddress;
emit Transfer(address(0), gnosisSafeAddress, i);
}
}
}
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the metadata URI.
/// @param _baseURI The new metadata URI.
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function tokenURI(uint256 id) public view override returns (string memory) {
return string(abi.encodePacked(baseURI, id.toString()));
}
/*///////////////////////////////////////////////////////////////
DUTCH AUCTION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin
/// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price.
function validCalculatedTokenPrice() private view returns (uint) {
uint priceReduction = ((block.timestamp - auctionStartTime) / 10 minutes) * 0.1 ether;
return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0;
}
/// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price.
/// @return The current dutch auction price
function getCurrentTokenPrice() public view returns (uint256) {
return max(validCalculatedTokenPrice(), 0.2 ether);
}
/// @notice Purchases a Pixelmon NFT in the dutch auction
/// @param mintingTwo True if the user is minting two Pixelmon, otherwise false.
/// @dev balanceOf is fine, team is aware and accepts that transferring out and repurchasing can be done, even by contracts.
function auction(bool mintingTwo) public payable {
if(block.timestamp < auctionStartTime || block.timestamp > auctionStartTime + 1 days) revert AuctionNotStarted();
uint count = mintingTwo ? 2 : 1;
uint price = getCurrentTokenPrice();
if(totalSupply + count > auctionSupply) revert MintedOut();
if(balanceOf[msg.sender] + count > 2) revert MintingTooMany();
if(msg.value < price * count) revert ValueTooLow();
mintingTwo ? _mintTwo(msg.sender) : _mint(msg.sender, totalSupply);
}
/// @notice Mints two Pixelmons to an address
/// @param to Receiver of the two newly minted NFTs
/// @dev errors taken from super._mint
function _mintTwo(address to) internal {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[totalSupply] == address(0), "ALREADY_MINTED");
uint currentId = totalSupply;
/// @dev unchecked because no arithmetic can overflow
unchecked {
totalSupply += 2;
balanceOf[to] += 2;
ownerOf[currentId] = to;
ownerOf[currentId + 1] = to;
emit Transfer(address(0), to, currentId);
emit Transfer(address(0), to, currentId + 1);
}
}
/*///////////////////////////////////////////////////////////////
MINTLIST MINT LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the price of the mintlist. To be called before uploading the mintlist.
/// @param price The price in wei of a Pixelmon NFT to be purchased from the mintlist supply.
function setMintlistPrice(uint256 price) public onlyOwner {
mintlistPrice = price;
}
/// @notice Allows the contract deployer to add a single address to the mintlist.
/// @param user Address to be added to the mintlist.
function mintlistUser(address user) public onlyOwner {
mintlisted[user] = true;
}
/// @notice Allows the contract deployer to add a list of addresses to the mintlist.
/// @param users Addresses to be added to the mintlist.
function mintlistUsers(address[] calldata users) public onlyOwner {
for (uint256 i = 0; i < users.length; i++) {
mintlisted[users[i]] = true;
}
}
/// @notice Purchases a Pixelmon NFT from the mintlist supply
/// @dev We do not check if auction is over because the mintlist will be uploaded after the auction.
function mintlistMint() public payable {
if(totalSupply >= secondEvolutionOffset) revert MintedOut();
if(!mintlisted[msg.sender]) revert NotMintlisted();
if(msg.value < mintlistPrice) revert ValueTooLow();
mintlisted[msg.sender] = false;
_mint(msg.sender, totalSupply);
}
/// @notice Withdraws collected funds to the Gnosis Safe address
function withdraw() public onlyOwner {
(bool success, ) = gnosisSafeAddress.call{value: address(this).balance}("");
require(success);
}
/*///////////////////////////////////////////////////////////////
ROLL OVER LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to airdrop Pixelmon to a list of addresses, in case the auction doesn't mint out
/// @param addresses Array of addresses to receive Pixelmon
function rollOverPixelmons(address[] calldata addresses) public onlyOwner {
if(totalSupply + addresses.length > secondEvolutionOffset) revert MintedOut();
for (uint256 i = 0; i < addresses.length; i++) {
_mint(msg.sender, totalSupply);
}
}
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Sets the address of the contract permitted to call mintEvolvedPixelmon
/// @param _serumContract The address of the EvolutionSerum contract
function setSerumContract(address _serumContract) public onlyOwner {
serumContract = _serumContract;
}
/// @notice Mints an evolved Pixelmon
/// @param receiver Receiver of the evolved Pixelmon
/// @param evolutionStage The evolution (2-4) that the Pixelmon is undergoing
function mintEvolvedPixelmon(address receiver, uint evolutionStage) public payable {
if(msg.sender != serumContract) revert UnauthorizedEvolution();
if (evolutionStage == 2) {
if(secondEvolutionSupply >= 4013) revert MintedOut();
_mint(receiver, secondEvolutionOffset + secondEvolutionSupply);
unchecked {
secondEvolutionSupply++;
}
} else if (evolutionStage == 3) {
if(thirdEvolutionSupply >= 1206) revert MintedOut();
_mint(receiver, thirdEvolutionOffset + thirdEvolutionSupply);
unchecked {
thirdEvolutionSupply++;
}
} else if (evolutionStage == 4) {
if(fourthEvolutionSupply >= 33) revert MintedOut();
_mint(receiver, fourthEvolutionOffset + fourthEvolutionSupply);
unchecked {
fourthEvolutionSupply++;
}
} else {
revert UnknownEvolution();
}
}
/*///////////////////////////////////////////////////////////////
UTILS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the greater of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
|
Allows the contract deployer to add a single address to the mintlist. user Address to be added to the mintlist.
|
function mintlistUser(address user) public onlyOwner {
mintlisted[user] = true;
}
| 12,826,997
|
./partial_match/42/0xbE9c6ca17259a874f96e3bC2776ae8E65ACc762e/sources/BController.sol
|
Validates transfer and reverts on rejection. May emit logs. bToken Asset being transferred src The account which sources the tokens dst The account which receives the tokens transferTokens The number of bTokens to transfer/ Shh - currently unused Shh - we don't ever want this hook to be marked pure
|
function transferVerify(address bToken, address src, address dst, uint transferTokens) external {
bToken;
src;
dst;
transferTokens;
if (false) {
maxAssets = maxAssets;
}
}
| 3,400,036
|
./partial_match/43113/0x26639692ec4bFB0767f505BbEbC871b84C3D4bbE/sources/contracts/SingleStakeFactory_flattened.sol
|
Takes fee for contract creation. SingleStakeFactory must be approved to spend the feeToken before creating a new farm./
|
function _takeFee() private {
require(
feeToken.balanceOf(msg.sender) >= fee,
"Creator cannot pay fee"
);
feeToken.safeTransferFrom(msg.sender, address(this), fee);
}
| 16,909,135
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts 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), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts 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), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @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 ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.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.
Counters.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 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 returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
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];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.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.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @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 = Math.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;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05`
* (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value
* {ERC20} uses, unless {_setupDecimals} is called.
*
* NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic
* of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
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) {
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: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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 returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
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 `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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
|
Disables this Voting contract in favor of the migrated one. Can only be called by the contract owner. newVotingAddress the newly migrated contract address./
|
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
| 99,059
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title A sample vault contract
/// @author William Starr & Coinocracy Inc.
/// @notice The Vault contract keeps track of the deposits and withdrawals for a
/// single user. The vault takes a 0.3% fee on every withdrawal. The vault contract
/// supports deposits and withdrawals for any ERC-20, but only one ERC-20 token
/// can be used per vault contract.
/// @dev Security for the Vault contract is paramount :) You can assume that the
/// owner of the Vault contract is the first account in Ganache (accounts[0]
/// within Vault.ts), and that the user of the vault is not the owner of the Vault
/// contract (e.g. the user of the vault is accounts[1] within Vault.ts, not
/// accounts[0]).
contract Vault {
// The contract address for USD token
address public ERC20_ADDRESS;
address public VAULT_FEE_ADDRESS;
uint256 balance = 0;
// The vault should take a fee of 0.3% on every withdrawal. For example, if a
// user is withdrawing 1000 USD, the vault should receive 3 USD. If a user is
// withdrawing 100 USD, the vault should receive .3 USD.
// The vaultFee is set using setVaultFee();
uint256 vaultFee = 0;
/// @notice Set the address for the USD token the vault will use
/// @param _token The address of the token contract
function setERCAddress(address _token) public {
ERC20_ADDRESS = _token;
}
/// @notice Set the address for the fee address the vault will use
/// @param _address The address of the fee receiver
function setVaultFeeAddress(address _address) public {
VAULT_FEE_ADDRESS = _address;
}
/// @notice Process a deposit to the vault
/// @param amount The amount that a user wants to deposit
/// @return balance The current account balance
function deposit(uint256 amount) public returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Transfer funds from the user to the vault
erc20.transferFrom(msg.sender, address(this), amount);
// Increase the balance by the deposit amount and return the balance
balance += amount;
return balance;
}
/// @notice Process a withdrawal from the vault
/// @param amount The amount that a user wants to withdraw. The vault takes a
/// 0.3% fee on every withdrawal
/// @return balance The current account balance
function withdraw(uint256 amount) public returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Calculate the fee that is owed to the vault
(uint256 amountToUser, uint256 amountToVault) = calculateVaultFee(amount);
erc20.transfer(msg.sender, amountToUser);
// Decrease the balance by the amount sent to the user
balance -= amountToUser;
erc20.transfer(VAULT_FEE_ADDRESS, amountToVault);
// Decrease the balance by the amount sent to the vault
balance -= amountToVault;
return balance;
}
/// @notice Calculate the fee that should go to the vault
/// @param amount The amount that a fee should be deducted from
/// @return A tuple of (amountToUser, amountToVault)
function calculateVaultFee(uint256 amount)
public
view
returns (uint256, uint256)
{
// TODO: Implement the 0.3% fee to the vault here
uint256 amountToVault = amount * vaultFee;
uint256 amountToUser = amount - amountToVault;
return (amountToUser, amountToVault);
}
/// @notice Set the fee that the vault takes
/// @param fee The fee that vaultFee should be set to
/// @return vaultFee The new value of the vault fee
function setVaultFee(uint256 fee) public returns (uint256) {
vaultFee = fee;
return vaultFee;
}
/// @notice Get the user's vault balance
/// @return balance The balance of the user
function getBalanceForVaultUser() public view returns (uint256) {
return balance;
}
}
|
Calculate the fee that should go to the vault amount The amount that a fee should be deducted from return A tuple of (amountToUser, amountToVault) TODO: Implement the 0.3% fee to the vault here
|
function calculateVaultFee(uint256 amount)
public
view
returns (uint256, uint256)
{
uint256 amountToVault = amount * vaultFee;
uint256 amountToUser = amount - amountToVault;
return (amountToUser, amountToVault);
}
| 1,790,995
|
./full_match/4/0x478eb6a735733BfC5764e7afB427B9088DF7df4f/sources/contracts/FarmAuction.sol
|
Allows the owner to set the Operator address (to run Auction rounds) _operatorAddress: address of the new operator Callable by owner/
|
function setOperatorAddress(address _operatorAddress) external onlyOwner {
require(_operatorAddress != address(0), "Management: Cannot be zero address");
operatorAddress = _operatorAddress;
emit NewOperatorAddress(_operatorAddress);
}
| 788,662
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./DaoStaking.sol";
import "./RicVault.sol";
// The FeeDao is where the fees accumulate from the contracts in the catalog.
// Token holders can Vote on IERC20 addresses to use for fees.
// Token holders can exchange their tokens for reward from up to 3 IERC20 balances.
// The exchanged tokens are added to the DaoStaking developer reward pool.
struct TokenProposal {
address creator;
string name;
IERC20 proposal;
string discussionURL;
uint256 approvals;
uint256 rejections;
uint256 created;
bool closed;
}
struct Token {
string name; // The name of the token
IERC20 token;
}
uint256 constant requiredBalance = 10000e18;
uint256 constant precision = 1000000000; //The precision of reward calculation, 9 decimals
enum Balance {
current,
total
}
enum Periods {
singleLock,
trippleLock,
pollPeriod
}
contract FeeDao {
using SafeERC20 for IERC20;
DaoStaking private staking;
CatalogDao private catalogDao;
RicVault private ricVault;
IERC20 private ric;
TokenProposal[] private proposals;
mapping(bytes32 => bool) private voted;
mapping(address => TokenProposal[]) private myProposals;
mapping(address => bool) private hasPendingProposal;
Token[] private tokens;
// addressAdded is used like a .contains array method for the tokens .
// will return true if the address has been added
mapping(address => bool) private addressAdded;
mapping(bytes32 => uint256) private balance;
mapping(Periods => uint256) private periods;
address private owner;
bool private lock;
event ProposeNewToken(
address indexed _address,
IERC20 _token,
string _discussionURL
);
event VoteOnToken(address indexed _address, bool _accepted, uint256 _index);
event CloseProposal(address indexed _address, uint256 index);
event WithdrawToken(
address indexed _address,
IERC20 withdraw,
uint256 amount,
uint256 reward
);
event WithdrawThreeTokens(
address indexed _address,
IERC20 first,
IERC20 second,
IERC20 third,
uint256 amount,
uint256 firstReward,
uint256 secondReward,
uint256 thirdReward
);
event Received(address to, uint256 value);
event WithdrawEth(address to, uint256 reward, uint256 ricAmount);
constructor(
IERC20 ric_,
DaoStaking _staking_,
CatalogDao _catalogDao_,
uint256 pollPeriod_
) {
ric = ric_;
staking = _staking_;
periods[Periods.pollPeriod] = pollPeriod_;
periods[Periods.singleLock] = 1314900; //blocks are around 1 month with 2 second finality
periods[Periods.trippleLock] = 3944700; // blocks are around 3 months with a 2 second finality
owner = msg.sender;
catalogDao = _catalogDao_;
balance[hashBalance(Balance.current)] = 0;
balance[hashBalance(Balance.total)] = 0;
}
function setRicVault(RicVault _ricVault_) external {
require(msg.sender == owner, "937");
ricVault = _ricVault_;
}
function setPollPeriods(
uint256 singleLock,
uint256 trippleLock,
uint256 pollPeriod
) external {
require(msg.sender == owner, "937");
periods[Periods.singleLock] = singleLock;
periods[Periods.trippleLock] = trippleLock;
periods[Periods.pollPeriod] = pollPeriod;
}
function proposeNewToken(
IERC20 _token,
string memory _discussionURL,
string memory _name_
) external returns (uint256) {
require(address(_token) != address(0), "948");
require(staking.isStaking(msg.sender), "919");
require(catalogDao.getRank(msg.sender) > 0, "911");
// The proposer must have the required balance
require(ric.balanceOf(msg.sender) > requiredBalance, "932");
require(!hasPendingProposal[msg.sender], "944");
TokenProposal memory proposal = TokenProposal({
name: _name_,
creator: msg.sender,
proposal: _token,
discussionURL: _discussionURL,
approvals: 0,
rejections: 0,
created: block.number,
closed: false
});
hasPendingProposal[msg.sender] = true;
proposals.push(proposal);
bytes32 _hash_ = hashTokenProposal(proposal, msg.sender);
voted[_hash_] = true;
myProposals[msg.sender].push(proposal);
emit ProposeNewToken(msg.sender, _token, _discussionURL);
return proposals.length;
}
function hashTokenProposal(TokenProposal memory _proposal, address _voter)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
_proposal.creator,
_proposal.proposal,
_proposal.discussionURL,
_proposal.created,
_voter
)
);
}
// Accessing array by index here!
function votedAlready(uint256 index, address _voter)
public
view
returns (bool)
{
bytes32 _hash_ = hashTokenProposal(proposals[index], _voter);
return voted[_hash_];
}
function voteOnToken(uint256 index, bool accepted) external {
require(staking.isStaking(msg.sender), "919");
require(catalogDao.getRank(msg.sender) > 0, "911");
// The voter must have the required balance
require(ric.balanceOf(msg.sender) > requiredBalance, "932");
bytes32 _hash_ = hashTokenProposal(proposals[index], msg.sender);
require(!voted[_hash_], "933");
// check if the voting period is over
require(
proposals[index].created + periods[Periods.pollPeriod] >
block.number,
"913"
);
if (accepted) {
proposals[index].approvals += 1;
// The deployer of the contract can moderate proposals
if (msg.sender == owner) {
proposals[index].approvals += 4;
}
} else {
proposals[index].rejections += 1;
if (msg.sender == owner) {
proposals[index].rejections += 4;
}
}
voted[_hash_] = true;
emit VoteOnToken(msg.sender, accepted, index);
}
function closeTokenProposal(uint256 index) external {
require(catalogDao.getRank(msg.sender) > 0, "911");
// Everybody closes their own proposals
require(proposals[index].creator == msg.sender, "914");
// The poll period must be over
require(
proposals[index].created + periods[Periods.pollPeriod] <
block.number,
"915"
);
require(!proposals[index].closed, "917");
proposals[index].closed = true;
hasPendingProposal[msg.sender] = false;
// If there are more approvals than rejections
if (proposals[index].approvals > proposals[index].rejections) {
tokens.push(
Token({
name: proposals[index].name,
token: proposals[index].proposal
})
);
addressAdded[address(proposals[index].proposal)] = true;
}
// else its closed, done.
emit CloseProposal(msg.sender, index);
}
function tokenHashWithAddress(Token memory _tokens_)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked(_tokens_.name, _tokens_.token, msg.sender)
);
}
function getTokens() external view returns (Token[] memory) {
return tokens;
}
function getProposals() external view returns (TokenProposal[] memory) {
return proposals;
}
function getMyProposals() external view returns (TokenProposal[] memory) {
return myProposals[msg.sender];
}
function calculateWithdraw(IERC20 from, uint256 amount)
public
view
returns (uint256 payment)
{
// How much is the amount compared to the total supply?
uint256 withPadding = amount * precision;
uint256 dividedByTotal = (withPadding / ric.totalSupply());
uint256 calculatedValue = dividedByTotal *
from.balanceOf(address(this));
payment = calculatedValue / precision;
}
function calculateETHWithdraw(uint256 amount)
public
view
returns (uint256 payment)
{
// How much is the amount compared to the total supply?
uint256 withPadding = amount * precision;
uint256 dividedByTotal = (withPadding / ric.totalSupply());
uint256 calculatedValue = dividedByTotal *
balance[hashBalance(Balance.current)];
payment = calculatedValue / precision;
}
function withdrawETH(uint256 amount) external {
require(!lock, "925");
lock = true;
require(ric.balanceOf(msg.sender) >= amount, "934");
uint256 _reward = calculateETHWithdraw(amount);
require(_reward < balance[hashBalance(Balance.current)], "927");
balance[hashBalance(Balance.current)] -= _reward;
// Lock the ric in the vault
ricVault.lockFor(msg.sender, periods[Periods.singleLock], amount);
// reduce the balance and send it
Address.sendValue(payable(msg.sender), _reward);
lock = false;
emit WithdrawEth(msg.sender, _reward, amount);
}
receive() external payable {
emit Received(msg.sender, msg.value);
balance[hashBalance(Balance.current)] += msg.value;
balance[hashBalance(Balance.total)] += msg.value;
}
function getCurrentBalance() external view returns (uint256) {
return balance[hashBalance(Balance.current)];
}
function getTotalBalance() external view returns (uint256) {
return balance[hashBalance(Balance.total)];
}
function withdrawOne(IERC20 from, uint256 amount) external {
require(!lock, "935");
lock = true;
require(addressAdded[address(from)], "939");
require(ric.balanceOf(msg.sender) >= amount, "934");
uint256 _reward = calculateWithdraw(from, amount);
require(_reward < from.balanceOf(address(this)), "927");
// Register a spend
balance[hashBalance(address(from))] += _reward;
// Lock the ric in the vault
ricVault.lockFor(msg.sender, periods[Periods.trippleLock], amount);
// transfer the requiested tokens
from.safeTransfer(msg.sender, _reward);
lock = false;
emit WithdrawToken(msg.sender, from, amount, _reward);
}
function viewSpentBalanceOf(IERC20 _token_)
external
view
returns (uint256)
{
return balance[hashBalance(address(_token_))];
}
function hashBalance(Balance _balance_) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_balance_));
}
// hashBalance with the address parameter is used for IERC20 address spent balance tracking
// It was done like this because of the limit on variable declarations in the contract
function hashBalance(address _balance_) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_balance_));
}
}
|
Accessing array by index here!
|
function votedAlready(uint256 index, address _voter)
public
view
returns (bool)
{
bytes32 _hash_ = hashTokenProposal(proposals[index], _voter);
return voted[_hash_];
}
| 2,473,263
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../base/Multicall.sol";
import "../bancor/BancorFormula.sol";
import "../upgrades/GraphUpgradeable.sol";
import "../utils/TokenUtils.sol";
import "./IGNS.sol";
import "./GNSStorage.sol";
/**
* @title GNS
* @dev The Graph Name System contract provides a decentralized naming system for subgraphs
* used in the scope of the Graph Network. It translates Subgraphs into Subgraph Versions.
* Each version is associated with a Subgraph Deployment. The contract has no knowledge of
* human-readable names. All human readable names emitted in events.
* The contract implements a multicall behaviour to support batching multiple calls in a single
* transaction.
*/
contract GNS is GNSV2Storage, GraphUpgradeable, IGNS, Multicall {
using SafeMath for uint256;
// -- Constants --
uint256 private constant MAX_UINT256 = 2**256 - 1;
// 100% in parts per million
uint32 private constant MAX_PPM = 1000000;
// Equates to Connector weight on bancor formula to be CW = 1
uint32 private constant defaultReserveRatio = 1000000;
// -- Events --
event SubgraphNFTUpdated(address subgraphNFT);
/**
* @dev Emitted when graph account sets its default name
*/
event SetDefaultName(
address indexed graphAccount,
uint256 nameSystem, // only ENS for now
bytes32 nameIdentifier,
string name
);
/**
* @dev Emitted when the subgraph metadata is updated.
*/
event SubgraphMetadataUpdated(uint256 indexed subgraphID, bytes32 subgraphMetadata);
/**
* @dev Emitted when a subgraph version is updated.
*/
event SubgraphVersionUpdated(
uint256 indexed subgraphID,
bytes32 indexed subgraphDeploymentID,
bytes32 versionMetadata
);
/**
* @dev Emitted when a curator mints signal.
*/
event SignalMinted(
uint256 indexed subgraphID,
address indexed curator,
uint256 nSignalCreated,
uint256 vSignalCreated,
uint256 tokensDeposited
);
/**
* @dev Emitted when a curator burns signal.
*/
event SignalBurned(
uint256 indexed subgraphID,
address indexed curator,
uint256 nSignalBurnt,
uint256 vSignalBurnt,
uint256 tokensReceived
);
/**
* @dev Emitted when a subgraph is created.
*/
event SubgraphPublished(
uint256 indexed subgraphID,
bytes32 indexed subgraphDeploymentID,
uint32 reserveRatio
);
/**
* @dev Emitted when a subgraph is upgraded to point to a new
* subgraph deployment, burning all the old vSignal and depositing the GRT into the
* new vSignal curve.
*/
event SubgraphUpgraded(
uint256 indexed subgraphID,
uint256 vSignalCreated,
uint256 tokensSignalled,
bytes32 indexed subgraphDeploymentID
);
/**
* @dev Emitted when a subgraph is deprecated.
*/
event SubgraphDeprecated(uint256 indexed subgraphID, uint256 withdrawableGRT);
/**
* @dev Emitted when a curator withdraws GRT from a deprecated subgraph
*/
event GRTWithdrawn(
uint256 indexed subgraphID,
address indexed curator,
uint256 nSignalBurnt,
uint256 withdrawnGRT
);
// -- Modifiers --
/**
* @dev Emitted when a legacy subgraph is claimed
*/
event LegacySubgraphClaimed(address indexed graphAccount, uint256 subgraphNumber);
/**
* @dev Modifier that allows only a subgraph operator to be the caller
*/
modifier onlySubgraphAuth(uint256 _subgraphID) {
require(ownerOf(_subgraphID) == msg.sender, "GNS: Must be authorized");
_;
}
// -- Functions --
/**
* @dev Initialize this contract.
*/
function initialize(
address _controller,
address _bondingCurve,
address _subgraphNFT
) external onlyImpl {
Managed._initialize(_controller);
// Dependencies
bondingCurve = _bondingCurve;
// Settings
_setOwnerTaxPercentage(500000);
_setSubgraphNFT(_subgraphNFT);
}
/**
* @dev Approve curation contract to pull funds.
*/
function approveAll() external override {
graphToken().approve(address(curation()), MAX_UINT256);
}
// -- Config --
/**
* @dev Set the owner fee percentage. This is used to prevent a subgraph owner to drain all
* the name curators tokens while upgrading or deprecating and is configurable in parts per million.
* @param _ownerTaxPercentage Owner tax percentage
*/
function setOwnerTaxPercentage(uint32 _ownerTaxPercentage) external override onlyGovernor {
_setOwnerTaxPercentage(_ownerTaxPercentage);
}
/**
* @dev Internal: Set the owner tax percentage. This is used to prevent a subgraph owner to drain all
* the name curators tokens while upgrading or deprecating and is configurable in parts per million.
* @param _ownerTaxPercentage Owner tax percentage
*/
function _setOwnerTaxPercentage(uint32 _ownerTaxPercentage) private {
require(_ownerTaxPercentage <= MAX_PPM, "Owner tax must be MAX_PPM or less");
ownerTaxPercentage = _ownerTaxPercentage;
emit ParameterUpdated("ownerTaxPercentage");
}
/**
* @dev Set the NFT registry contract
* NOTE: Calling this function will break the ownership model unless
* it is replaced with a fully migrated version of the NFT contract state
* Use with care.
* @param _subgraphNFT Address of the ERC721 contract
*/
function setSubgraphNFT(address _subgraphNFT) public onlyGovernor {
_setSubgraphNFT(_subgraphNFT);
}
/**
* @dev Internal: Set the NFT registry contract
* @param _subgraphNFT Address of the ERC721 contract
*/
function _setSubgraphNFT(address _subgraphNFT) private {
require(
_subgraphNFT != address(0) && Address.isContract(_subgraphNFT),
"NFT must be valid"
);
subgraphNFT = ISubgraphNFT(_subgraphNFT);
emit SubgraphNFTUpdated(_subgraphNFT);
}
// -- Actions --
/**
* @dev Allows a graph account to set a default name
* @param _graphAccount Account that is setting its name
* @param _nameSystem Name system account already has ownership of a name in
* @param _nameIdentifier The unique identifier that is used to identify the name in the system
* @param _name The name being set as default
*/
function setDefaultName(
address _graphAccount,
uint8 _nameSystem,
bytes32 _nameIdentifier,
string calldata _name
) external override {
require(_graphAccount == msg.sender, "GNS: Only you can set your name");
emit SetDefaultName(_graphAccount, _nameSystem, _nameIdentifier, _name);
}
/**
* @dev Allows a subgraph owner to update the metadata of a subgraph they have published
* @param _subgraphID Subgraph ID
* @param _subgraphMetadata IPFS hash for the subgraph metadata
*/
function updateSubgraphMetadata(uint256 _subgraphID, bytes32 _subgraphMetadata)
public
override
onlySubgraphAuth(_subgraphID)
{
_setSubgraphMetadata(_subgraphID, _subgraphMetadata);
}
/**
* @dev Publish a new subgraph.
* @param _subgraphDeploymentID Subgraph deployment for the subgraph
* @param _versionMetadata IPFS hash for the subgraph version metadata
* @param _subgraphMetadata IPFS hash for the subgraph metadata
*/
function publishNewSubgraph(
bytes32 _subgraphDeploymentID,
bytes32 _versionMetadata,
bytes32 _subgraphMetadata
) external override notPaused {
// Subgraph deployment must be non-empty
require(_subgraphDeploymentID != 0, "GNS: Cannot set deploymentID to 0 in publish");
// Init the subgraph
address subgraphOwner = msg.sender;
uint256 subgraphID = _nextSubgraphID(subgraphOwner);
SubgraphData storage subgraphData = _getSubgraphData(subgraphID);
subgraphData.subgraphDeploymentID = _subgraphDeploymentID;
subgraphData.reserveRatio = defaultReserveRatio;
// Mint the NFT. Use the subgraphID as tokenID.
// This function will check the if tokenID already exists.
_mintNFT(subgraphOwner, subgraphID);
emit SubgraphPublished(subgraphID, _subgraphDeploymentID, defaultReserveRatio);
// Set the token metadata
_setSubgraphMetadata(subgraphID, _subgraphMetadata);
emit SubgraphVersionUpdated(subgraphID, _subgraphDeploymentID, _versionMetadata);
}
/**
* @dev Publish a new version of an existing subgraph.
* @param _subgraphID Subgraph ID
* @param _subgraphDeploymentID Subgraph deployment ID of the new version
* @param _versionMetadata IPFS hash for the subgraph version metadata
*/
function publishNewVersion(
uint256 _subgraphID,
bytes32 _subgraphDeploymentID,
bytes32 _versionMetadata
) external override notPaused onlySubgraphAuth(_subgraphID) {
// Perform the upgrade from the current subgraph deployment to the new one.
// This involves burning all signal from the old deployment and using the funds to buy
// from the new deployment.
// This will also make the change to target to the new deployment.
// Subgraph check
SubgraphData storage subgraphData = _getSubgraphOrRevert(_subgraphID);
// New subgraph deployment must be non-empty
require(_subgraphDeploymentID != 0, "GNS: Cannot set deploymentID to 0 in publish");
// New subgraph deployment must be different than current
require(
_subgraphDeploymentID != subgraphData.subgraphDeploymentID,
"GNS: Cannot publish a new version with the same subgraph deployment ID"
);
// This is to prevent the owner from front running its name curators signal by posting
// its own signal ahead, bringing the name curators in, and dumping on them
ICuration curation = curation();
require(
!curation.isCurated(_subgraphDeploymentID),
"GNS: Owner cannot point to a subgraphID that has been pre-curated"
);
// Move all signal from previous version to new version
// NOTE: We will only do this as long as there is signal on the subgraph
if (subgraphData.nSignal > 0) {
// Burn all version signal in the name pool for tokens (w/no slippage protection)
// Sell all signal from the old deployment
uint256 tokens = curation.burn(
subgraphData.subgraphDeploymentID,
subgraphData.vSignal,
0
);
// Take the owner cut of the curation tax, add it to the total
// Upgrade is only callable by the owner, we assume then that msg.sender = owner
address subgraphOwner = msg.sender;
uint256 tokensWithTax = _chargeOwnerTax(
tokens,
subgraphOwner,
curation.curationTaxPercentage()
);
// Update pool: constant nSignal, vSignal can change (w/no slippage protection)
// Buy all signal from the new deployment
(subgraphData.vSignal, ) = curation.mint(_subgraphDeploymentID, tokensWithTax, 0);
emit SubgraphUpgraded(
_subgraphID,
subgraphData.vSignal,
tokensWithTax,
_subgraphDeploymentID
);
}
// Update target deployment
subgraphData.subgraphDeploymentID = _subgraphDeploymentID;
emit SubgraphVersionUpdated(_subgraphID, _subgraphDeploymentID, _versionMetadata);
}
/**
* @dev Deprecate a subgraph. The bonding curve is destroyed, the vSignal is burned, and the GNS
* contract holds the GRT from burning the vSignal, which all curators can withdraw manually.
* Can only be done by the subgraph owner.
* @param _subgraphID Subgraph ID
*/
function deprecateSubgraph(uint256 _subgraphID)
external
override
notPaused
onlySubgraphAuth(_subgraphID)
{
// Subgraph check
SubgraphData storage subgraphData = _getSubgraphOrRevert(_subgraphID);
// Burn signal only if it has any available
if (subgraphData.nSignal > 0) {
subgraphData.withdrawableGRT = curation().burn(
subgraphData.subgraphDeploymentID,
subgraphData.vSignal,
0
);
}
// Deprecate the subgraph and do cleanup
subgraphData.disabled = true;
subgraphData.vSignal = 0;
subgraphData.reserveRatio = 0;
// NOTE: We don't reset the following variable as we use it to test if the Subgraph was ever created
// subgraphData.subgraphDeploymentID = 0;
// Burn the NFT
_burnNFT(_subgraphID);
emit SubgraphDeprecated(_subgraphID, subgraphData.withdrawableGRT);
}
/**
* @dev Deposit GRT into a subgraph and mint signal.
* @param _subgraphID Subgraph ID
* @param _tokensIn The amount of tokens the nameCurator wants to deposit
* @param _nSignalOutMin Expected minimum amount of name signal to receive
*/
function mintSignal(
uint256 _subgraphID,
uint256 _tokensIn,
uint256 _nSignalOutMin
) external override notPartialPaused {
// Subgraph checks
SubgraphData storage subgraphData = _getSubgraphOrRevert(_subgraphID);
// Pull tokens from sender
address curator = msg.sender;
TokenUtils.pullTokens(graphToken(), curator, _tokensIn);
// Get name signal to mint for tokens deposited
(uint256 vSignal, ) = curation().mint(subgraphData.subgraphDeploymentID, _tokensIn, 0);
uint256 nSignal = vSignalToNSignal(_subgraphID, vSignal);
// Slippage protection
require(nSignal >= _nSignalOutMin, "GNS: Slippage protection");
// Update pools
subgraphData.vSignal = subgraphData.vSignal.add(vSignal);
subgraphData.nSignal = subgraphData.nSignal.add(nSignal);
subgraphData.curatorNSignal[curator] = subgraphData.curatorNSignal[curator].add(nSignal);
emit SignalMinted(_subgraphID, curator, nSignal, vSignal, _tokensIn);
}
/**
* @dev Burn signal for a subgraph and return the GRT.
* @param _subgraphID Subgraph ID
* @param _nSignal The amount of nSignal the nameCurator wants to burn
* @param _tokensOutMin Expected minimum amount of tokens to receive
*/
function burnSignal(
uint256 _subgraphID,
uint256 _nSignal,
uint256 _tokensOutMin
) external override notPartialPaused {
// Subgraph checks
SubgraphData storage subgraphData = _getSubgraphOrRevert(_subgraphID);
// Curator balance checks
address curator = msg.sender;
uint256 curatorNSignal = subgraphData.curatorNSignal[curator];
require(
_nSignal <= curatorNSignal,
"GNS: Curator cannot withdraw more nSignal than they have"
);
// Get tokens for name signal amount to burn
uint256 vSignal = nSignalToVSignal(_subgraphID, _nSignal);
uint256 tokens = curation().burn(subgraphData.subgraphDeploymentID, vSignal, _tokensOutMin);
// Update pools
subgraphData.vSignal = subgraphData.vSignal.sub(vSignal);
subgraphData.nSignal = subgraphData.nSignal.sub(_nSignal);
subgraphData.curatorNSignal[curator] = subgraphData.curatorNSignal[curator].sub(_nSignal);
// Return the tokens to the nameCurator
require(graphToken().transfer(curator, tokens), "GNS: Error sending tokens");
emit SignalBurned(_subgraphID, curator, _nSignal, vSignal, tokens);
}
/**
* @dev Withdraw tokens from a deprecated subgraph.
* When the subgraph is deprecated, any curator can call this function and
* withdraw the GRT they are entitled for its original deposit
* @param _subgraphID Subgraph ID
*/
function withdraw(uint256 _subgraphID) external override notPartialPaused {
// Subgraph validations
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
require(subgraphData.disabled == true, "GNS: Must be disabled first");
require(subgraphData.withdrawableGRT > 0, "GNS: No more GRT to withdraw");
// Curator validations
address curator = msg.sender;
uint256 curatorNSignal = subgraphData.curatorNSignal[curator];
require(curatorNSignal > 0, "GNS: No signal to withdraw GRT");
// Get curator share of tokens to be withdrawn
uint256 tokensOut = curatorNSignal.mul(subgraphData.withdrawableGRT).div(
subgraphData.nSignal
);
subgraphData.curatorNSignal[curator] = 0;
subgraphData.nSignal = subgraphData.nSignal.sub(curatorNSignal);
subgraphData.withdrawableGRT = subgraphData.withdrawableGRT.sub(tokensOut);
// Return tokens to the curator
TokenUtils.pushTokens(graphToken(), curator, tokensOut);
emit GRTWithdrawn(_subgraphID, curator, curatorNSignal, tokensOut);
}
/**
* @dev Calculate tax that owner will have to cover for upgrading or deprecating.
* @param _tokens Tokens that were received from deprecating the old subgraph
* @param _owner Subgraph owner
* @param _curationTaxPercentage Tax percentage on curation deposits from Curation contract
* @return Total tokens that will be sent to curation, _tokens + ownerTax
*/
function _chargeOwnerTax(
uint256 _tokens,
address _owner,
uint32 _curationTaxPercentage
) private returns (uint256) {
if (_curationTaxPercentage == 0 || ownerTaxPercentage == 0) {
return 0;
}
// Tax on the total bonding curve funds
uint256 taxOnOriginal = _tokens.mul(_curationTaxPercentage).div(MAX_PPM);
// Total after the tax
uint256 totalWithoutOwnerTax = _tokens.sub(taxOnOriginal);
// The portion of tax that the owner will pay
uint256 ownerTax = taxOnOriginal.mul(ownerTaxPercentage).div(MAX_PPM);
uint256 totalWithOwnerTax = totalWithoutOwnerTax.add(ownerTax);
// The total after tax, plus owner partial repay, divided by
// the tax, to adjust it slightly upwards. ex:
// 100 GRT, 5 GRT Tax, owner pays 100% --> 5 GRT
// To get 100 in the protocol after tax, Owner deposits
// ~5.26, as ~105.26 * .95 = 100
uint256 totalAdjustedUp = totalWithOwnerTax.mul(MAX_PPM).div(
uint256(MAX_PPM).sub(uint256(_curationTaxPercentage))
);
uint256 ownerTaxAdjustedUp = totalAdjustedUp.sub(_tokens);
// Get the owner of the subgraph to reimburse the curation tax
TokenUtils.pullTokens(graphToken(), _owner, ownerTaxAdjustedUp);
return totalAdjustedUp;
}
/**
* @dev Calculate subgraph signal to be returned for an amount of tokens.
* @param _subgraphID Subgraph ID
* @param _tokensIn Tokens being exchanged for subgraph signal
* @return Amount of subgraph signal and curation tax
*/
function tokensToNSignal(uint256 _subgraphID, uint256 _tokensIn)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
(uint256 vSignal, uint256 curationTax) = curation().tokensToSignal(
subgraphData.subgraphDeploymentID,
_tokensIn
);
uint256 nSignal = vSignalToNSignal(_subgraphID, vSignal);
return (vSignal, nSignal, curationTax);
}
/**
* @dev Calculate tokens returned for an amount of subgraph signal.
* @param _subgraphID Subgraph ID
* @param _nSignalIn Subgraph signal being exchanged for tokens
* @return Amount of tokens returned for an amount of subgraph signal
*/
function nSignalToTokens(uint256 _subgraphID, uint256 _nSignalIn)
public
view
override
returns (uint256, uint256)
{
// Get subgraph or revert if not published
// It does not make sense to convert signal from a disabled or non-existing one
SubgraphData storage subgraphData = _getSubgraphOrRevert(_subgraphID);
uint256 vSignal = nSignalToVSignal(_subgraphID, _nSignalIn);
uint256 tokensOut = curation().signalToTokens(subgraphData.subgraphDeploymentID, vSignal);
return (vSignal, tokensOut);
}
/**
* @dev Calculate subgraph signal to be returned for an amount of subgraph deployment signal.
* @param _subgraphID Subgraph ID
* @param _vSignalIn Amount of subgraph deployment signal to exchange for subgraph signal
* @return Amount of subgraph signal that can be bought
*/
function vSignalToNSignal(uint256 _subgraphID, uint256 _vSignalIn)
public
view
override
returns (uint256)
{
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
// Handle initialization by using 1:1 version to name signal
if (subgraphData.vSignal == 0) {
return _vSignalIn;
}
return
BancorFormula(bondingCurve).calculatePurchaseReturn(
subgraphData.nSignal,
subgraphData.vSignal,
subgraphData.reserveRatio,
_vSignalIn
);
}
/**
* @dev Calculate subgraph deployment signal to be returned for an amount of subgraph signal.
* @param _subgraphID Subgraph ID
* @param _nSignalIn Subgraph signal being exchanged for subgraph deployment signal
* @return Amount of subgraph deployment signal that can be returned
*/
function nSignalToVSignal(uint256 _subgraphID, uint256 _nSignalIn)
public
view
override
returns (uint256)
{
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
return
BancorFormula(bondingCurve).calculateSaleReturn(
subgraphData.nSignal,
subgraphData.vSignal,
subgraphData.reserveRatio,
_nSignalIn
);
}
/**
* @dev Get the amount of subgraph signal a curator has.
* @param _subgraphID Subgraph ID
* @param _curator Curator address
* @return Amount of subgraph signal owned by a curator
*/
function getCuratorSignal(uint256 _subgraphID, address _curator)
public
view
override
returns (uint256)
{
return _getSubgraphData(_subgraphID).curatorNSignal[_curator];
}
/**
* @dev Return the total signal on the subgraph.
* @param _subgraphID Subgraph ID
* @return Total signal on the subgraph
*/
function subgraphSignal(uint256 _subgraphID) external view override returns (uint256) {
return _getSubgraphData(_subgraphID).nSignal;
}
/**
* @dev Return the total tokens on the subgraph at current value.
* @param _subgraphID Subgraph ID
* @return Total tokens on the subgraph
*/
function subgraphTokens(uint256 _subgraphID) external view override returns (uint256) {
uint256 signal = _getSubgraphData(_subgraphID).nSignal;
if (signal > 0) {
(, uint256 tokens) = nSignalToTokens(_subgraphID, signal);
return tokens;
}
return 0;
}
/**
* @dev Create subgraphID for legacy subgraph and mint ownership NFT.
* @param _graphAccount Account that created the subgraph
* @param _subgraphNumber The sequence number of the created subgraph
* @param _subgraphMetadata IPFS hash for the subgraph metadata
*/
function migrateLegacySubgraph(
address _graphAccount,
uint256 _subgraphNumber,
bytes32 _subgraphMetadata
) external {
// Must be an existing legacy subgraph
bool legacySubgraphExists = legacySubgraphData[_graphAccount][_subgraphNumber]
.subgraphDeploymentID != 0;
require(legacySubgraphExists == true, "GNS: Subgraph does not exist");
// Must not be a claimed subgraph
uint256 subgraphID = _buildSubgraphID(_graphAccount, _subgraphNumber);
require(
legacySubgraphKeys[subgraphID].account == address(0),
"GNS: Subgraph was already claimed"
);
// Store a reference for a legacy subgraph
legacySubgraphKeys[subgraphID] = IGNS.LegacySubgraphKey({
account: _graphAccount,
accountSeqID: _subgraphNumber
});
// Delete state for legacy subgraph
legacySubgraphs[_graphAccount][_subgraphNumber] = 0;
// Mint the NFT and send to owner
// The subgraph owner is the graph account that created it
_mintNFT(_graphAccount, subgraphID);
emit LegacySubgraphClaimed(_graphAccount, _subgraphNumber);
// Set the token metadata
_setSubgraphMetadata(subgraphID, _subgraphMetadata);
}
/**
* @dev Return whether a subgraph is published.
* @param _subgraphID Subgraph ID
* @return Return true if subgraph is currently published
*/
function isPublished(uint256 _subgraphID) public view override returns (bool) {
return _isPublished(_getSubgraphData(_subgraphID));
}
/**
* @dev Build a subgraph ID based on the account creating it and a sequence number for that account.
* Subgraph ID is the keccak hash of account+seqID
* @return Subgraph ID
*/
function _buildSubgraphID(address _account, uint256 _seqID) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_account, _seqID)));
}
/**
* @dev Return the next subgraphID given the account that is creating the subgraph.
* NOTE: This function updates the sequence ID for the account
* @return Sequence ID for the account
*/
function _nextSubgraphID(address _account) internal returns (uint256) {
return _buildSubgraphID(_account, _nextAccountSeqID(_account));
}
/**
* @dev Return a new consecutive sequence ID for an account and update to the next value.
* NOTE: This function updates the sequence ID for the account
* @return Sequence ID for the account
*/
function _nextAccountSeqID(address _account) internal returns (uint256) {
uint256 seqID = nextAccountSeqID[_account];
nextAccountSeqID[_account] = nextAccountSeqID[_account].add(1);
return seqID;
}
/**
* @dev Get subgraph data.
* This function will first look for a v1 subgraph and return it if found.
* @param _subgraphID Subgraph ID
* @return Subgraph Data
*/
function _getSubgraphData(uint256 _subgraphID) private view returns (SubgraphData storage) {
// If there is a legacy subgraph created return it
LegacySubgraphKey storage legacySubgraphKey = legacySubgraphKeys[_subgraphID];
if (legacySubgraphKey.account != address(0)) {
return legacySubgraphData[legacySubgraphKey.account][legacySubgraphKey.accountSeqID];
}
// Return new subgraph type
return subgraphs[_subgraphID];
}
/**
* @dev Return whether a subgraph is published.
* @param _subgraphData Subgraph Data
* @return Return true if subgraph is currently published
*/
function _isPublished(SubgraphData storage _subgraphData) internal view returns (bool) {
return _subgraphData.subgraphDeploymentID != 0 && _subgraphData.disabled == false;
}
/**
* @dev Return the subgraph data or revert if not published or deprecated.
* @param _subgraphID Subgraph ID
* @return Subgraph Data
*/
function _getSubgraphOrRevert(uint256 _subgraphID)
internal
view
returns (SubgraphData storage)
{
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
require(_isPublished(subgraphData) == true, "GNS: Must be active");
return subgraphData;
}
// -- NFT --
/**
* @dev Return the owner of a subgraph.
* @param _tokenID Subgraph ID
* @return Owner address
*/
function ownerOf(uint256 _tokenID) public view override returns (address) {
return subgraphNFT.ownerOf(_tokenID);
}
/**
* @dev Mint the NFT for the subgraph.
* @param _owner Owner address
* @param _tokenID Subgraph ID
*/
function _mintNFT(address _owner, uint256 _tokenID) internal {
subgraphNFT.mint(_owner, _tokenID);
}
/**
* @dev Burn the NFT for the subgraph.
* @param _tokenID Subgraph ID
*/
function _burnNFT(uint256 _tokenID) internal {
subgraphNFT.burn(_tokenID);
}
/**
* @dev Set the subgraph metadata.
* @param _tokenID Subgraph ID
* @param _subgraphMetadata IPFS hash of the subgraph metadata
*/
function _setSubgraphMetadata(uint256 _tokenID, bytes32 _subgraphMetadata) internal {
subgraphNFT.setSubgraphMetadata(_tokenID, _subgraphMetadata);
// Even if the following event is emitted in the NFT we emit it here to facilitate
// subgraph indexing
emit SubgraphMetadataUpdated(_tokenID, _subgraphMetadata);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./IMulticall.sol";
// Inspired by https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/base/Multicall.sol
// Note: Removed payable from the multicall
/**
* @title Multicall
* @notice Enables calling multiple methods in a single call to the contract
*/
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract BancorFormula {
using SafeMath for uint256;
uint16 public constant version = 6;
uint256 private constant ONE = 1;
uint32 private constant MAX_RATIO = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
* @dev Auto-generated via 'PrintIntScalingFactors.py'
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
* @dev Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
* @dev Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
* @dev Auto-generated via 'PrintFunctionConstructor.py'
*/
uint256[128] private maxExpArray;
constructor() {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
* @dev given a token supply, reserve balance, ratio and a deposit amount (in the reserve token),
* calculates the return for a given conversion (in the main token)
*
* Formula:
* Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 1000000) - 1)
*
* @param _supply token total supply
* @param _reserveBalance total reserve balance
* @param _reserveRatio reserve ratio, represented in ppm, 1-1000000
* @param _depositAmount deposit amount, in reserve token
*
* @return purchase return amount
*/
function calculatePurchaseReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _depositAmount
) public view returns (uint256) {
// validate input
require(
_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO,
"invalid parameters"
);
// special case for 0 deposit amount
if (_depositAmount == 0) return 0;
// special case if the ratio = 100%
if (_reserveRatio == MAX_RATIO) return _supply.mul(_depositAmount) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_reserveBalance);
(result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_RATIO);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a token supply, reserve balance, ratio and a sell amount (in the main token),
* calculates the return for a given conversion (in the reserve token)
*
* Formula:
* Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1000000 / _reserveRatio))
*
* @param _supply token total supply
* @param _reserveBalance total reserve
* @param _reserveRatio constant reserve Ratio, represented in ppm, 1-1000000
* @param _sellAmount sell amount, in the token itself
*
* @return sale return amount
*/
function calculateSaleReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _sellAmount
) public view returns (uint256) {
// validate input
require(
_supply > 0 &&
_reserveBalance > 0 &&
_reserveRatio > 0 &&
_reserveRatio <= MAX_RATIO &&
_sellAmount <= _supply,
"invalid parameters"
);
// special case for 0 sell amount
if (_sellAmount == 0) return 0;
// special case for selling the entire supply
if (_sellAmount == _supply) return _reserveBalance;
// special case if the ratio = 100%
if (_reserveRatio == MAX_RATIO) return _reserveBalance.mul(_sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_RATIO, _reserveRatio);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given two reserve balances/ratios and a sell amount (in the first reserve token),
* calculates the return for a conversion from the first reserve token to the second reserve token (in the second reserve token)
* note that prior to version 4, you should use 'calculateCrossConnectorReturn' instead
*
* Formula:
* Return = _toReserveBalance * (1 - (_fromReserveBalance / (_fromReserveBalance + _amount)) ^ (_fromReserveRatio / _toReserveRatio))
*
* @param _fromReserveBalance input reserve balance
* @param _fromReserveRatio input reserve ratio, represented in ppm, 1-1000000
* @param _toReserveBalance output reserve balance
* @param _toReserveRatio output reserve ratio, represented in ppm, 1-1000000
* @param _amount input reserve amount
*
* @return second reserve amount
*/
function calculateCrossReserveReturn(
uint256 _fromReserveBalance,
uint32 _fromReserveRatio,
uint256 _toReserveBalance,
uint32 _toReserveRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(
_fromReserveBalance > 0 &&
_fromReserveRatio > 0 &&
_fromReserveRatio <= MAX_RATIO &&
_toReserveBalance > 0 &&
_toReserveRatio > 0 &&
_toReserveRatio <= MAX_RATIO
);
// special case for equal ratios
if (_fromReserveRatio == _toReserveRatio)
return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromReserveBalance.add(_amount);
(result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio);
uint256 temp1 = _toReserveBalance.mul(result);
uint256 temp2 = _toReserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given a smart token supply, reserve balance, total ratio and an amount of requested smart tokens,
* calculates the amount of reserve tokens required for purchasing the given amount of smart tokens
*
* Formula:
* Return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_RATIO / _totalRatio) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve token balance
* @param _totalRatio total ratio, represented in ppm, 2-2000000
* @param _amount requested amount of smart tokens
*
* @return amount of reserve tokens
*/
function calculateFundCost(
uint256 _supply,
uint256 _reserveBalance,
uint32 _totalRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(
_supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2
);
// special case for 0 amount
if (_amount == 0) return 0;
// special case if the total ratio = 100%
if (_totalRatio == MAX_RATIO) return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
uint256 result;
uint8 precision;
uint256 baseN = _supply.add(_amount);
(result, precision) = power(baseN, _supply, MAX_RATIO, _totalRatio);
uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1;
return temp - _reserveBalance;
}
/**
* @dev given a smart token supply, reserve balance, total ratio and an amount of smart tokens to liquidate,
* calculates the amount of reserve tokens received for selling the given amount of smart tokens
*
* Formula:
* Return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_RATIO / _totalRatio))
*
* @param _supply smart token supply
* @param _reserveBalance reserve token balance
* @param _totalRatio total ratio, represented in ppm, 2-2000000
* @param _amount amount of smart tokens to liquidate
*
* @return amount of reserve tokens
*/
function calculateLiquidateReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _totalRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(
_supply > 0 &&
_reserveBalance > 0 &&
_totalRatio > 1 &&
_totalRatio <= MAX_RATIO * 2 &&
_amount <= _supply
);
// special case for 0 amount
if (_amount == 0) return 0;
// special case for liquidating the entire supply
if (_amount == _supply) return _reserveBalance;
// special case if the total ratio = 100%
if (_totalRatio == MAX_RATIO) return _amount.mul(_reserveBalance) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_RATIO, _totalRatio);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev General Description:
* Determine a value of precision.
* Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
* Return the result along with the precision used.
*
* Detailed Description:
* Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
* The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
* The larger "precision" is, the more accurately this value represents the real value.
* However, the larger "precision" is, the more bits are required in order to store this value.
* And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
* This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
* Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
* This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
* This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
* Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD".
*/
function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = (_baseN * FIXED_1) / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
} else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = (baseLog * _expN) / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
} else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (
generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision),
precision
);
}
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1.
* This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return (res * LN2_NUMERATOR) / LN2_DENOMINATOR;
}
/**
* @dev computes the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
} else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
* @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
* - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
* - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x) lo = mid;
else hi = mid;
}
if (maxExpArray[hi] >= _x) return hi;
if (maxExpArray[lo] >= _x) return lo;
require(false);
return 0;
}
/**
* @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
* it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
* it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
* the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
* the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision;
res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision;
res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision;
res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision;
res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision;
res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision;
res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision;
res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1
* Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
* Auto-generated via 'PrintFunctionOptimalLog.py'
* Detailed description:
* - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
* - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
* - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
* - The natural logarithm of the input is calculated by summing up the intermediate results above
* - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {
res += 0x40000000000000000000000000000000;
x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8;
} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {
res += 0x20000000000000000000000000000000;
x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7;
} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {
res += 0x10000000000000000000000000000000;
x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1;
} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {
res += 0x08000000000000000000000000000000;
x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8;
} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {
res += 0x04000000000000000000000000000000;
x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3;
} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {
res += 0x02000000000000000000000000000000;
x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2;
} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {
res += 0x01000000000000000000000000000000;
x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99;
} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {
res += 0x00800000000000000000000000000000;
x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733;
} // add 1 / 2^8
z = y = x - FIXED_1;
w = (y * y) / FIXED_1;
res +=
(z * (0x100000000000000000000000000000000 - y)) /
0x100000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02
res +=
(z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) /
0x200000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04
res +=
(z * (0x099999999999999999999999999999999 - y)) /
0x300000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06
res +=
(z * (0x092492492492492492492492492492492 - y)) /
0x400000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08
res +=
(z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) /
0x500000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10
res +=
(z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) /
0x600000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12
res +=
(z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) /
0x700000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14
res +=
(z * (0x088888888888888888888888888888888 - y)) /
0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
* @dev computes e ^ (x / FIXED_1) * FIXED_1
* input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
* auto-generated via 'PrintFunctionOptimalExp.py'
* Detailed description:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = (z * y) / FIXED_1;
res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / FIXED_1;
res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / FIXED_1;
res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / FIXED_1;
res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / FIXED_1;
res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / FIXED_1;
res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / FIXED_1;
res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / FIXED_1;
res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / FIXED_1;
res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / FIXED_1;
res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / FIXED_1;
res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / FIXED_1;
res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / FIXED_1;
res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / FIXED_1;
res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / FIXED_1;
res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / FIXED_1;
res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0)
res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0)
res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0)
res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0)
res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0)
res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0)
res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0)
res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossConnectorReturn(
uint256 _fromConnectorBalance,
uint32 _fromConnectorWeight,
uint256 _toConnectorBalance,
uint32 _toConnectorWeight,
uint256 _amount
) public view returns (uint256) {
return
calculateCrossReserveReturn(
_fromConnectorBalance,
_fromConnectorWeight,
_toConnectorBalance,
_toConnectorWeight,
_amount
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "./IGraphProxy.sol";
/**
* @title Graph Upgradeable
* @dev This contract is intended to be inherited from upgradeable contracts.
*/
contract GraphUpgradeable {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Check if the caller is the proxy admin.
*/
modifier onlyProxyAdmin(IGraphProxy _proxy) {
require(msg.sender == _proxy.admin(), "Caller must be the proxy admin");
_;
}
/**
* @dev Check if the caller is the implementation.
*/
modifier onlyImpl() {
require(msg.sender == _implementation(), "Caller must be the implementation");
_;
}
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Accept to be an implementation of proxy.
*/
function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) {
_proxy.acceptUpgrade();
}
/**
* @dev Accept to be an implementation of proxy and then call a function from the new
* implementation as specified by `_data`, which should be an encoded function call. This is
* useful to initialize new storage variables in the proxied contract.
*/
function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data)
external
onlyProxyAdmin(_proxy)
{
_proxy.acceptUpgradeAndCall(_data);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "../token/IGraphToken.sol";
library TokenUtils {
/**
* @dev Pull tokens from an address to this contract.
* @param _graphToken Token to transfer
* @param _from Address sending the tokens
* @param _amount Amount of tokens to transfer
*/
function pullTokens(
IGraphToken _graphToken,
address _from,
uint256 _amount
) internal {
if (_amount > 0) {
require(_graphToken.transferFrom(_from, address(this), _amount), "!transfer");
}
}
/**
* @dev Push tokens from this contract to a receiving address.
* @param _graphToken Token to transfer
* @param _to Address receiving the tokens
* @param _amount Amount of tokens to transfer
*/
function pushTokens(
IGraphToken _graphToken,
address _to,
uint256 _amount
) internal {
if (_amount > 0) {
require(_graphToken.transfer(_to, _amount), "!transfer");
}
}
/**
* @dev Burn tokens held by this contract.
* @param _graphToken Token to burn
* @param _amount Amount of tokens to burn
*/
function burnTokens(IGraphToken _graphToken, uint256 _amount) internal {
if (_amount > 0) {
_graphToken.burn(_amount);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
interface IGNS {
// -- Pool --
struct SubgraphData {
uint256 vSignal; // The token of the subgraph-deployment bonding curve
uint256 nSignal; // The token of the subgraph bonding curve
mapping(address => uint256) curatorNSignal;
bytes32 subgraphDeploymentID;
uint32 reserveRatio;
bool disabled;
uint256 withdrawableGRT;
}
struct LegacySubgraphKey {
address account;
uint256 accountSeqID;
}
// -- Configuration --
function approveAll() external;
function setOwnerTaxPercentage(uint32 _ownerTaxPercentage) external;
// -- Publishing --
function setDefaultName(
address _graphAccount,
uint8 _nameSystem,
bytes32 _nameIdentifier,
string calldata _name
) external;
function updateSubgraphMetadata(uint256 _subgraphID, bytes32 _subgraphMetadata) external;
function publishNewSubgraph(
bytes32 _subgraphDeploymentID,
bytes32 _versionMetadata,
bytes32 _subgraphMetadata
) external;
function publishNewVersion(
uint256 _subgraphID,
bytes32 _subgraphDeploymentID,
bytes32 _versionMetadata
) external;
function deprecateSubgraph(uint256 _subgraphID) external;
// -- Curation --
function mintSignal(
uint256 _subgraphID,
uint256 _tokensIn,
uint256 _nSignalOutMin
) external;
function burnSignal(
uint256 _subgraphID,
uint256 _nSignal,
uint256 _tokensOutMin
) external;
function withdraw(uint256 _subgraphID) external;
// -- Getters --
function ownerOf(uint256 _tokenID) external view returns (address);
function subgraphSignal(uint256 _subgraphID) external view returns (uint256);
function subgraphTokens(uint256 _subgraphID) external view returns (uint256);
function tokensToNSignal(uint256 _subgraphID, uint256 _tokensIn)
external
view
returns (
uint256,
uint256,
uint256
);
function nSignalToTokens(uint256 _subgraphID, uint256 _nSignalIn)
external
view
returns (uint256, uint256);
function vSignalToNSignal(uint256 _subgraphID, uint256 _vSignalIn)
external
view
returns (uint256);
function nSignalToVSignal(uint256 _subgraphID, uint256 _nSignalIn)
external
view
returns (uint256);
function getCuratorSignal(uint256 _subgraphID, address _curator)
external
view
returns (uint256);
function isPublished(uint256 _subgraphID) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../governance/Managed.sol";
import "./erc1056/IEthereumDIDRegistry.sol";
import "./IGNS.sol";
import "./ISubgraphNFT.sol";
abstract contract GNSV1Storage is Managed {
// -- State --
// In parts per hundred
uint32 public ownerTaxPercentage;
// Bonding curve formula
address public bondingCurve;
// Stores what subgraph deployment a particular legacy subgraph targets
// A subgraph is defined by (graphAccountID, subgraphNumber)
// A subgraph can target one subgraph deployment (bytes32 hash)
// (graphAccountID, subgraphNumber) => subgraphDeploymentID
mapping(address => mapping(uint256 => bytes32)) internal legacySubgraphs;
// Every time an account creates a subgraph it increases a per-account sequence ID
// account => seqID
mapping(address => uint256) public nextAccountSeqID;
// Stores all the signal deposited on a legacy subgraph
// (graphAccountID, subgraphNumber) => SubgraphData
mapping(address => mapping(uint256 => IGNS.SubgraphData)) public legacySubgraphData;
// [DEPRECATED] ERC-1056 contract reference
// This contract is used for managing identities
IEthereumDIDRegistry private __DEPRECATED_erc1056Registry;
}
abstract contract GNSV2Storage is GNSV1Storage {
// Use it whenever a legacy (v1) subgraph NFT was claimed to maintain compatibility
// Keep a reference from subgraphID => (graphAccount, subgraphNumber)
mapping(uint256 => IGNS.LegacySubgraphKey) public legacySubgraphKeys;
// Store data for all NFT-based (v2) subgraphs
// subgraphID => SubgraphData
mapping(uint256 => IGNS.SubgraphData) public subgraphs;
// Contract that represents subgraph ownership through an NFT
ISubgraphNFT public subgraphNFT;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
/**
* @title Multicall interface
* @notice Enables calling multiple methods in a single call to the contract
*/
interface IMulticall {
/**
* @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
* @param data The encoded function data for each of the calls to make to this contract
* @return results The results from each of the calls passed in via data
*/
function multicall(bytes[] calldata data) external returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
interface IGraphProxy {
function admin() external returns (address);
function setAdmin(address _newAdmin) external;
function implementation() external returns (address);
function pendingImplementation() external returns (address);
function upgradeTo(address _newImplementation) external;
function acceptUpgrade() external;
function acceptUpgradeAndCall(bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGraphToken is IERC20 {
// -- Mint and Burn --
function burn(uint256 amount) external;
function mint(address _to, uint256 _amount) external;
// -- Mint Admin --
function addMinter(address _account) external;
function removeMinter(address _account) external;
function renounceMinter() external;
function isMinter(address _account) external view returns (bool);
// -- Permit --
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "./IController.sol";
import "../curation/ICuration.sol";
import "../epochs/IEpochManager.sol";
import "../rewards/IRewardsManager.sol";
import "../staking/IStaking.sol";
import "../token/IGraphToken.sol";
/**
* @title Graph Managed contract
* @dev The Managed contract provides an interface to interact with the Controller.
* It also provides local caching for contract addresses. This mechanism relies on calling the
* public `syncAllContracts()` function whenever a contract changes in the controller.
*
* Inspired by Livepeer:
* https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol
*/
contract Managed {
// -- State --
// Controller that contract is registered with
IController public controller;
mapping(bytes32 => address) private addressCache;
uint256[10] private __gap;
// -- Events --
event ParameterUpdated(string param);
event SetController(address controller);
/**
* @dev Emitted when contract with `nameHash` is synced to `contractAddress`.
*/
event ContractSynced(bytes32 indexed nameHash, address contractAddress);
// -- Modifiers --
function _notPartialPaused() internal view {
require(!controller.paused(), "Paused");
require(!controller.partialPaused(), "Partial-paused");
}
function _notPaused() internal view {
require(!controller.paused(), "Paused");
}
function _onlyGovernor() internal view {
require(msg.sender == controller.getGovernor(), "Caller must be Controller governor");
}
function _onlyController() internal view {
require(msg.sender == address(controller), "Caller must be Controller");
}
modifier notPartialPaused() {
_notPartialPaused();
_;
}
modifier notPaused() {
_notPaused();
_;
}
// Check if sender is controller.
modifier onlyController() {
_onlyController();
_;
}
// Check if sender is the governor.
modifier onlyGovernor() {
_onlyGovernor();
_;
}
// -- Functions --
/**
* @dev Initialize the controller.
*/
function _initialize(address _controller) internal {
_setController(_controller);
}
/**
* @notice Set Controller. Only callable by current controller.
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
_setController(_controller);
}
/**
* @dev Set controller.
* @param _controller Controller contract address
*/
function _setController(address _controller) internal {
require(_controller != address(0), "Controller must be set");
controller = IController(_controller);
emit SetController(_controller);
}
/**
* @dev Return Curation interface.
* @return Curation contract registered with Controller
*/
function curation() internal view returns (ICuration) {
return ICuration(_resolveContract(keccak256("Curation")));
}
/**
* @dev Return EpochManager interface.
* @return Epoch manager contract registered with Controller
*/
function epochManager() internal view returns (IEpochManager) {
return IEpochManager(_resolveContract(keccak256("EpochManager")));
}
/**
* @dev Return RewardsManager interface.
* @return Rewards manager contract registered with Controller
*/
function rewardsManager() internal view returns (IRewardsManager) {
return IRewardsManager(_resolveContract(keccak256("RewardsManager")));
}
/**
* @dev Return Staking interface.
* @return Staking contract registered with Controller
*/
function staking() internal view returns (IStaking) {
return IStaking(_resolveContract(keccak256("Staking")));
}
/**
* @dev Return GraphToken interface.
* @return Graph token contract registered with Controller
*/
function graphToken() internal view returns (IGraphToken) {
return IGraphToken(_resolveContract(keccak256("GraphToken")));
}
/**
* @dev Resolve a contract address from the cache or the Controller if not found.
* @return Address of the contract
*/
function _resolveContract(bytes32 _nameHash) internal view returns (address) {
address contractAddress = addressCache[_nameHash];
if (contractAddress == address(0)) {
contractAddress = controller.getContractProxy(_nameHash);
}
return contractAddress;
}
/**
* @dev Cache a contract address from the Controller registry.
* @param _name Name of the contract to sync into the cache
*/
function _syncContract(string memory _name) internal {
bytes32 nameHash = keccak256(abi.encodePacked(_name));
address contractAddress = controller.getContractProxy(nameHash);
if (addressCache[nameHash] != contractAddress) {
addressCache[nameHash] = contractAddress;
emit ContractSynced(nameHash, contractAddress);
}
}
/**
* @dev Sync protocol contract addresses from the Controller registry.
* This function will cache all the contracts using the latest addresses
* Anyone can call the function whenever a Proxy contract change in the
* controller to ensure the protocol is using the latest version
*/
function syncAllContracts() external {
_syncContract("Curation");
_syncContract("EpochManager");
_syncContract("RewardsManager");
_syncContract("Staking");
_syncContract("GraphToken");
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IEthereumDIDRegistry {
function identityOwner(address identity) external view returns (address);
function setAttribute(
address identity,
bytes32 name,
bytes calldata value,
uint256 validity
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface ISubgraphNFT is IERC721 {
// -- Config --
function setMinter(address _minter) external;
function setTokenDescriptor(address _tokenDescriptor) external;
function setBaseURI(string memory _baseURI) external;
// -- Actions --
function mint(address _to, uint256 _tokenId) external;
function burn(uint256 _tokenId) external;
function setSubgraphMetadata(uint256 _tokenId, bytes32 _subgraphMetadata) external;
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.12 <0.8.0;
interface IController {
function getGovernor() external view returns (address);
// -- Registry --
function setContractProxy(bytes32 _id, address _contractAddress) external;
function unsetContractProxy(bytes32 _id) external;
function updateController(bytes32 _id, address _controller) external;
function getContractProxy(bytes32 _id) external view returns (address);
// -- Pausing --
function setPartialPaused(bool _partialPaused) external;
function setPaused(bool _paused) external;
function setPauseGuardian(address _newPauseGuardian) external;
function paused() external view returns (bool);
function partialPaused() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "./IGraphCurationToken.sol";
interface ICuration {
// -- Configuration --
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external;
function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external;
function setCurationTaxPercentage(uint32 _percentage) external;
function setCurationTokenMaster(address _curationTokenMaster) external;
// -- Curation --
function mint(
bytes32 _subgraphDeploymentID,
uint256 _tokensIn,
uint256 _signalOutMin
) external returns (uint256, uint256);
function burn(
bytes32 _subgraphDeploymentID,
uint256 _signalIn,
uint256 _tokensOutMin
) external returns (uint256);
function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external;
// -- Getters --
function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool);
function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256);
function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256);
function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn)
external
view
returns (uint256, uint256);
function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn)
external
view
returns (uint256);
function curationTaxPercentage() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
interface IEpochManager {
// -- Configuration --
function setEpochLength(uint256 _epochLength) external;
// -- Epochs
function runEpoch() external;
// -- Getters --
function isCurrentEpochRun() external view returns (bool);
function blockNum() external view returns (uint256);
function blockHash(uint256 _block) external view returns (bytes32);
function currentEpoch() external view returns (uint256);
function currentEpochBlock() external view returns (uint256);
function currentEpochBlockSinceStart() external view returns (uint256);
function epochsSince(uint256 _epoch) external view returns (uint256);
function epochsSinceUpdate() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
interface IRewardsManager {
/**
* @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment.
*/
struct Subgraph {
uint256 accRewardsForSubgraph;
uint256 accRewardsForSubgraphSnapshot;
uint256 accRewardsPerSignalSnapshot;
uint256 accRewardsPerAllocatedToken;
}
// -- Params --
function setIssuanceRate(uint256 _issuanceRate) external;
// -- Denylist --
function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external;
function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external;
function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny)
external;
function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool);
// -- Getters --
function getNewRewardsPerSignal() external view returns (uint256);
function getAccRewardsPerSignal() external view returns (uint256);
function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID)
external
view
returns (uint256, uint256);
function getRewards(address _allocationID) external view returns (uint256);
// -- Updates --
function updateAccRewardsPerSignal() external returns (uint256);
function takeRewards(address _allocationID) external returns (uint256);
// -- Hooks --
function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.12 <0.8.0;
pragma abicoder v2;
import "./IStakingData.sol";
interface IStaking is IStakingData {
// -- Allocation Data --
/**
* @dev Possible states an allocation can be
* States:
* - Null = indexer == address(0)
* - Active = not Null && tokens > 0
* - Closed = Active && closedAtEpoch != 0
* - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now()
* - Claimed = not Null && tokens == 0
*/
enum AllocationState {
Null,
Active,
Closed,
Finalized,
Claimed
}
// -- Configuration --
function setMinimumIndexerStake(uint256 _minimumIndexerStake) external;
function setThawingPeriod(uint32 _thawingPeriod) external;
function setCurationPercentage(uint32 _percentage) external;
function setProtocolPercentage(uint32 _percentage) external;
function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external;
function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external;
function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external;
function setDelegationRatio(uint32 _delegationRatio) external;
function setDelegationParameters(
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) external;
function setDelegationParametersCooldown(uint32 _blocks) external;
function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external;
function setDelegationTaxPercentage(uint32 _percentage) external;
function setSlasher(address _slasher, bool _allowed) external;
function setAssetHolder(address _assetHolder, bool _allowed) external;
// -- Operation --
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
// -- Staking --
function stake(uint256 _tokens) external;
function stakeTo(address _indexer, uint256 _tokens) external;
function unstake(uint256 _tokens) external;
function slash(
address _indexer,
uint256 _tokens,
uint256 _reward,
address _beneficiary
) external;
function withdraw() external;
function setRewardsDestination(address _destination) external;
// -- Delegation --
function delegate(address _indexer, uint256 _tokens) external returns (uint256);
function undelegate(address _indexer, uint256 _shares) external returns (uint256);
function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256);
// -- Channel management and allocations --
function allocate(
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function allocateFrom(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function closeAllocation(address _allocationID, bytes32 _poi) external;
function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external;
function closeAndAllocate(
address _oldAllocationID,
bytes32 _poi,
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function collect(uint256 _tokens, address _allocationID) external;
function claim(address _allocationID, bool _restake) external;
function claimMany(address[] calldata _allocationID, bool _restake) external;
// -- Getters and calculations --
function hasStake(address _indexer) external view returns (bool);
function getIndexerStakedTokens(address _indexer) external view returns (uint256);
function getIndexerCapacity(address _indexer) external view returns (uint256);
function getAllocation(address _allocationID) external view returns (Allocation memory);
function getAllocationState(address _allocationID) external view returns (AllocationState);
function isAllocation(address _allocationID) external view returns (bool);
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getDelegation(address _indexer, address _delegator)
external
view
returns (Delegation memory);
function isDelegator(address _indexer, address _delegator) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IGraphCurationToken is IERC20Upgradeable {
function initialize(address _owner) external;
function burnFrom(address _account, uint256 _amount) external;
function mint(address _to, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.12 <0.8.0;
interface IStakingData {
/**
* @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment
* An allocation is created in the allocate() function and consumed in claim()
*/
struct Allocation {
address indexer;
bytes32 subgraphDeploymentID;
uint256 tokens; // Tokens allocated to a SubgraphDeployment
uint256 createdAtEpoch; // Epoch when it was created
uint256 closedAtEpoch; // Epoch when it was closed
uint256 collectedFees; // Collected fees for the allocation
uint256 effectiveAllocation; // Effective allocation when closed
uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc
}
/**
* @dev Represents a request to close an allocation with a specific proof of indexing.
* This is passed when calling closeAllocationMany to define the closing parameters for
* each allocation.
*/
struct CloseAllocationRequest {
address allocationID;
bytes32 poi;
}
// -- Delegation Data --
/**
* @dev Delegation pool information. One per indexer.
*/
struct DelegationPool {
uint32 cooldownBlocks; // Blocks to wait before updating parameters
uint32 indexingRewardCut; // in PPM
uint32 queryFeeCut; // in PPM
uint256 updatedAtBlock; // Block when the pool was last updated
uint256 tokens; // Total tokens as pool reserves
uint256 shares; // Total shares minted in the pool
mapping(address => Delegation) delegators; // Mapping of delegator => Delegation
}
/**
* @dev Individual delegation data of a delegator in a pool.
*/
struct Delegation {
uint256 shares; // Shares owned by a delegator in the pool
uint256 tokensLocked; // Tokens locked for undelegation
uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 tokens from a deprecated subgraph. When the subgraph is deprecated, any curator can call this function and withdraw the GRT they are entitled for its original deposit _subgraphID Subgraph ID/ Subgraph validations Curator validations Get curator share of tokens to be withdrawn Return tokens to the curator
|
function withdraw(uint256 _subgraphID) external override notPartialPaused {
SubgraphData storage subgraphData = _getSubgraphData(_subgraphID);
require(subgraphData.disabled == true, "GNS: Must be disabled first");
require(subgraphData.withdrawableGRT > 0, "GNS: No more GRT to withdraw");
address curator = msg.sender;
uint256 curatorNSignal = subgraphData.curatorNSignal[curator];
require(curatorNSignal > 0, "GNS: No signal to withdraw GRT");
uint256 tokensOut = curatorNSignal.mul(subgraphData.withdrawableGRT).div(
subgraphData.nSignal
);
subgraphData.curatorNSignal[curator] = 0;
subgraphData.nSignal = subgraphData.nSignal.sub(curatorNSignal);
subgraphData.withdrawableGRT = subgraphData.withdrawableGRT.sub(tokensOut);
TokenUtils.pushTokens(graphToken(), curator, tokensOut);
emit GRTWithdrawn(_subgraphID, curator, curatorNSignal, tokensOut);
}
| 1,674,903
|
./full_match/1/0x2a8b06562A455A79f7027cEd093f1E9dC0fC53B2/sources/contracts/Converter.sol
|
Get the energy amount available for address `addr` addr The wallet address to get energy for periodId The period id for energy calculation return Energy amount available/ for LBA participants who didn't migrate LP, still use the old calculation logic that totalAE = AE remaing from staking + AE remaining from LBA LP
|
function getEnergy(address addr, uint256 periodId) public view virtual returns (uint256) {
if (stakingLogic_.lbaMigrated(addr)) {
uint256 generatedEnergy = calculateEnergy(addr, periodId);
uint256 consumedEnergy = getConsumedEnergy(addr) + getConsumedLBAEnergy(addr);
uint256 remainingEnergy = generatedEnergy > consumedEnergy ? generatedEnergy - consumedEnergy : 0;
return remainingEnergy;
uint256 generatedEnergy = calculateEnergy(addr, periodId);
uint256 consumedEnergy = getConsumedEnergy(addr);
uint256 remainingEnergy = generatedEnergy > consumedEnergy ? generatedEnergy - consumedEnergy : 0;
return remainingEnergy + getRemainingLBAEnergy(addr, periodId);
}
}
| 2,906,649
|
./full_match/137/0xDef1C0ded9bec7F1a1670819833240f027b25EfF/sources/Users/jacob/projects/ethdev/0x/workspace-remote/workspace/0x-monorepo/contracts/zero-ex/contracts/src/storage/LibProxyStorage.sol
|
Get the storage bucket for this contract. Dip into assembly to change the slot pointed to by the local variable `stor`. See https:solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slotaccess-to-external-variables-functions-and-libraries
|
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.Proxy
);
}
| 4,670,732
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
/// @title An NFT that you can use to log in to a web2 site.
/// @author Rudy Hasbun
/// @notice use this contract to manage user roles for signing in to web2 sites.
contract NftId is ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
uint256 public immutable MAX_ROLE_SIZE = 30;
mapping(uint256 => mapping(address => string)) public tokenRoles;
constructor() ERC721("NFT ID", "NFTID") {}
/// @notice the url for each NFT will be this concatenated with the tokenId
/// @return base URI
function _baseURI() internal pure override returns (string memory) {
return "https://nftid.app/nft/";
}
/// @notice create a new NFT account that is transferred to `to`
/// @param to address which will own the NFT
function safeMintOnBehalfOf(address to) public {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
/// @notice create a new NFT account that will be owned by the message sender
function safeMint() public {
safeMintOnBehalfOf(msg.sender);
}
/// @notice a new role has been set for an NFT account
event SetRole(address indexed _user, uint256 indexed _tokenId);
/// @notice a role has been removed for an NFT account
event RemoveRole(address indexed _user, uint256 indexed _tokenId);
modifier isOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender, "Must be token owner");
_;
}
/// @notice set or change the role (any string) for a particular address
/// @param _tokenId id for NFT account
/// @param _user address which the new role will apply to
/// @param _role string that will be returned when authenticating with this address
function setRole(
uint256 _tokenId,
address _user,
string calldata _role
) public isOwnerOf(_tokenId) {
if (ownerOf(_tokenId) == _user)
revert("cannot change the role for the owner");
if (bytes(_role).length > MAX_ROLE_SIZE)
revert("max size for role exceeded");
mapping(address => string) storage roles = tokenRoles[_tokenId];
bytes memory currentRole = bytes(roles[_user]);
if (currentRole.length != 0) removeRole(_tokenId, _user);
roles[_user] = _role;
emit SetRole(_user, _tokenId);
}
/// @notice remove the role assigned to a particular address
/// @param _tokenId id for NFT account
/// @param _user address which will have its role removed
function removeRole(uint256 _tokenId, address _user)
public
isOwnerOf(_tokenId)
{
if (ownerOf(_tokenId) == _user)
revert("cannot change the role for the owner");
mapping(address => string) storage roles = tokenRoles[_tokenId];
delete roles[_user];
emit RemoveRole(_user, _tokenId);
}
/// @notice transfer NFT to a new owner
/// @dev See {IERC721-transferFrom}.
/// @param from current holder of NFT
/// @param to new holder of NFT
/// @param tokenId id for NFT account
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
preTransferCleanup(to, tokenId);
super.transferFrom(from, to, tokenId);
}
/// @notice transfer NFT to a new owner
/// @dev See {IERC721-safeTransferFrom}.
/// @param from current holder of NFT
/// @param to new holder of NFT
/// @param tokenId id for NFT account
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
preTransferCleanup(to, tokenId);
super.safeTransferFrom(from, to, tokenId);
}
/// @notice transfer NFT to a new owner
/// @dev See {IERC721-safeTransferFrom}.
/// @param from current holder of NFT
/// @param to new holder of NFT
/// @param tokenId id for NFT account
/// @param _data (not used)
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
preTransferCleanup(to, tokenId);
super.safeTransferFrom(from, to, tokenId, _data);
}
/// @notice transfer NFT to a new owner
/// @param to new holder of NFT
/// @param tokenId id for NFT account
function transfer(address to, uint256 tokenId) public {
preTransferCleanup(to, tokenId);
safeTransferFrom(ownerOf(tokenId), to, tokenId);
}
/// @notice before transferring, manage some cleanup
/// @param _to new holder of NFT
/// @param _tokenId id for NFT account
function preTransferCleanup(address _to, uint256 _tokenId) private {
bytes memory currentRole = bytes(tokenRoles[_tokenId][_to]);
if (currentRole.length != 0) removeRole(_tokenId, _to); // remove role because after transfer the new role will be "owner"
}
/// @notice this is the method that should be used to check for privileges for a particular address. If empty string is returned, the user has no privileges.
/// @param _user address that is trying to authenticate
/// @param _tokenId id for NFT account
/// @return the role for an authenticated user (or empty string if not authenticated)
function getRoleFor(address _user, uint256 _tokenId)
public
view
returns (string memory)
{
if (ownerOf(_tokenId) == _user) return "owner";
mapping(address => string) storage roles = tokenRoles[_tokenId];
return roles[_user];
}
}
|
transfer NFT to a new owner See {IERC721-safeTransferFrom}. from current holder of NFT to new holder of NFT tokenId id for NFT account
|
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
preTransferCleanup(to, tokenId);
super.safeTransferFrom(from, to, tokenId);
}
| 1,804,573
|
./full_match/1/0x9d1aE699b5A39BE51B63A16275e2586435F94610/sources/contracts/customExtension.sol
|
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 {
_mint(to, amount);
}
| 8,323,755
|
/**
*Submitted for verification at Etherscan.io on 2022-04-07
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
}
// File: contracts/interfaces/ILayerZeroEndpoint.sol
pragma solidity >=0.5.0;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication) external view returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
}
// File: contracts/interfaces/ILayerZeroReceiver.sol
pragma solidity >=0.5.0;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
}
// 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/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/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/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/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (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)) : "";
}
/**
* @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");
_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 {}
}
// File: contracts/NonblockingReceiver.sol
pragma solidity ^0.8.6;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract");
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload));
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public {
// only internal transaction
require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge.");
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal;
function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal {
endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam);
}
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce];
require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message");
require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner {
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
// File: contracts/GhostlyGhosts.sol
abstract contract Target721 {
function ownerOf(uint256 tokenId) public view virtual returns (address);
}
pragma solidity ^0.8.7;
contract OmniDiyApes is Ownable, ERC721, NonblockingReceiver{
address public _owner;
string private baseURI;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
uint256 nextTokenId = 0;
uint256 MAX_MINT_ETHEREUM = 6084;
uint256 internal MAX_TOKEN_ID;
uint gasForDestinationLzReceive = 350000;
bool internal burnAirdrop = false;
// 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;
mapping(uint256 => bool) private _tokenBifurcated;
uint256 public MINT_PRICE = 0.09 ether;
constructor(string memory baseURI_) ERC721("OmniDiyApes", "DAPE") {
_owner = msg.sender;
baseURI = baseURI_;
}
// mint function
// mint is , but payments are accepted
function mint(uint8 numTokens) external payable {
require(msg.value == MINT_PRICE * numTokens, "Invalid Ether amount sent.");
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(msg.sender, ++nextTokenId);
}
}
// airDropNFTHolder function
// mint is , but payments are accepted
function airDropNFTHolder(address[] calldata recipients) external onlyOwner {
uint256 startingSupply = nextTokenId;
// Update the total supply.
nextTokenId = startingSupply + recipients.length;
// Note: First token has ID #0.
for (uint256 i = 0; i < recipients.length; i++) {
_safeMint(recipients[i], startingSupply + i);
}
if((startingSupply + recipients.length - 1) > MAX_TOKEN_ID) { MAX_TOKEN_ID = (startingSupply + recipients.length - 1); }
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
address owner = _owners[tokenId];
if(owner == address(0) && !_tokenBifurcated[tokenId] && !burnAirdrop) {
try _target.ownerOf(tokenId) returns (address result) { owner = result; } catch { owner = address(0); }
}
return owner;
}
// This function transfers the nft from your address on the
// source chain to the same address on the destination chain
function traverseChains(uint16 _chainId, uint tokenId) public payable {
require(msg.sender == ownerOf(tokenId), "You must own the token to traverse");
require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel");
// burn NFT, eliminating it from circulation on src chain
_burn(tokenId);
// abi.encode() the payload with the values to send
bytes memory payload = abi.encode(msg.sender, tokenId);
// encode adapterParams to specify more gas for the destination
uint16 version = 1;
bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
// get the fees we need to pay to LayerZero + Relayer to cover message delivery
// you will be refunded for extra gas paid
(uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams);
require(msg.value >= messageFee, "OmniDiyApes: msg.value not enough to cover messageFee. Send gas for message fees");
endpoint.send{value: msg.value}(
_chainId, // destination chainId
trustedRemoteLookup[_chainId], // destination address of nft contract
payload, // abi.encoded()'ed bytes
payable(msg.sender), // refund address
address(0x0), // 'zroPaymentAddress' unused for this
adapterParams // txParameters
);
}
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
function donate() external payable {
// thank you
}
Target721 _target = Target721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D);
function setTargetContract(address contractAddress) external onlyOwner {
_target = Target721(contractAddress);
}
// This allows the devs to receive kind donations
function withdraw(uint amt) external onlyOwner {
(bool sent, ) = payable(_owner).call{value: amt}("");
require(sent, "OmniDiyApes: Failed to withdraw Ether");
}
// just in case this fixed variable limits us from future integrations
function setGasForDestinationLzReceive(uint newVal) external onlyOwner {
gasForDestinationLzReceive = newVal;
}
function _LzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
require(msg.sender == ownerOf(_srcChainId), "You must own the token to traverse");
require(msg.sender == ownerOf(_nonce), "You must own the token to traverse");
// decode
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
// decode
(address _toAddr, uint _tokenId) = abi.decode(_srcAddress, (address, uint));
// mint the tokens back into existence on destination chain
_safeMint(toAddr, tokenId);
_safeMint(_toAddr, _tokenId);
}
function _baseURI() override internal view returns (string memory) {
return baseURI;
}
}
|
mint function mint is , but payments are accepted
|
function mint(uint8 numTokens) external payable {
require(msg.value == MINT_PRICE * numTokens, "Invalid Ether amount sent.");
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(msg.sender, ++nextTokenId);
}
}
| 7,734,438
|
/**
*Submitted for verification at Etherscan.io on 2021-05-17
*/
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.4;
library SafeMathLib {
function times(uint a, uint b) public pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b, 'Overflow detected');
return c;
}
function minus(uint a, uint b) public pure returns (uint) {
require(b <= a, 'Underflow detected');
return a - b;
}
function plus(uint a, uint b) public pure returns (uint) {
uint c = a + b;
require(c>=a && c>=b, 'Overflow detected');
return c;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface Token {
/**
* @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);
}
// This contract is inspired by the harberger tax idea, it rewards people with FVT for burning their liquidity provider
// tokens.
contract LiquidityMining {
using SafeMathLib for uint;
// this represents a single recipient of token rewards on a fixed schedule that does not depend on deposit or burn rate
// it specifies an id (key to a map below) an marker for the last time it was updated, a deposit (of LP tokens) and a
// burn rate of those LP tokens per block, and finally, the owner of the slot, who will receive the rewards
struct Slot {
uint id;
uint lastUpdatedBlock;
uint deposit;
uint burnRate;
address owner;
}
// privileged key that can change key parameters, will change to dao later
address public management;
// the token that the rewards are made in
Token public rewardToken;
// the liquidity provider (LP) token
Token public liquidityToken;
// address to which taxes are sent
address public taxAddress;
// is the contract paused?
bool public paused = false;
// when was the contract paused?
uint public pausedBlock = 0;
// maximum number of slots, changeable by management key
uint public maxStakers = 0;
// current number of stakers
uint public numStakers = 0;
// minimum deposit allowable to claim a slot
uint public minimumDeposit = 0;
// maximum deposit allowable (used to limit risk)
uint public maximumDeposit = 1000 ether;
// minimum burn rate allowable to claim a slot
uint public minimumBurnRate = 0;
// total liquidity tokens staked
uint public totalStaked = 0;
// total rewards distributed
uint public totalRewards = 0;
// total LP tokens burned
uint public totalBurned = 0;
// start block used to compute rewards
uint public pulseStartBlock;
// the length of a single pulse of rewards, in blocks
uint public pulseWavelengthBlocks = 0;
// the amount of the highest per-block reward, in FVT
uint public pulseAmplitudeFVT = 0;
// computed constants for deferred computation
uint public pulseIntegral = 0;
uint public pulseConstant = 0;
// map of slot ids to slots
mapping (uint => Slot) public slots;
// map of addresses to amount staked
mapping (address => uint) public totalStakedFor;
// map of total rewards by address
mapping (address => uint) public totalRewardsFor;
// map of rewards for session slotId -> rewardsForThisSession
mapping (uint => uint) public rewardsForSession;
// map of total burned by address
mapping (address => uint) public totalBurnedFor;
event ManagementUpdated(address oldMgmt, address newMgmt);
event ContractPaused();
event ContractUnpaused();
event WavelengthUpdated(uint oldWavelength, uint newWavelength);
event AmplitudeUpdated(uint oldAmplitude, uint newAmplitude);
event MaxStakersUpdated(uint oldMaxStakers, uint newMaxStakers);
event MinDepositUpdated(uint oldMinDeposit, uint newMinDeposit);
event MaxDepositUpdated(uint oldMaxDeposit, uint newMaxDeposit);
event MinBurnRateUpdated(uint oldMinBurnRate, uint newMinBurnRate);
event SlotChangedHands(uint slotId, uint deposit, uint burnRate, address owner);
modifier managementOnly() {
require (msg.sender == management, 'Only management may call this');
_;
}
constructor(
address rewardTokenAddr,
address liquidityTokenAddr,
address mgmt,
address taxAddr,
uint pulseLengthBlocks,
uint pulseAmplitude,
uint mxStkrs) {
rewardToken = Token(rewardTokenAddr);
liquidityToken = Token(liquidityTokenAddr);
management = mgmt;
pulseStartBlock = block.number;
pulseWavelengthBlocks = pulseLengthBlocks;
pulseAmplitudeFVT = pulseAmplitude;
pulseConstant = pulseAmplitudeFVT / pulseWavelengthBlocks.times(pulseWavelengthBlocks);
pulseIntegral = pulseSum(pulseWavelengthBlocks);
maxStakers = mxStkrs;
taxAddress = taxAddr;
}
// only management can reset management key
function setManagement(address newMgmt) public managementOnly {
address oldMgmt = management;
management = newMgmt;
emit ManagementUpdated(oldMgmt, newMgmt);
}
function pauseContract() public managementOnly {
require(paused == false, 'Already paused');
paused = true;
pausedBlock = block.number;
emit ContractPaused();
}
function unpauseContract() public managementOnly {
require(paused == true, 'Already unpaused');
require(numStakers == 0, 'Must kick everyone out before unpausing');
paused = false;
pausedBlock = 0;
emit ContractUnpaused();
}
// change the number of slots, should be done with care
function setMaxStakers(uint newMaxStakers) public managementOnly {
uint oldMaxStakers = maxStakers;
maxStakers = newMaxStakers;
emit MaxStakersUpdated(oldMaxStakers, maxStakers);
}
// change the minimum deposit to acquire a slot
function setMinDeposit(uint newMinDeposit) public managementOnly {
uint oldMinDeposit = minimumDeposit;
minimumDeposit = newMinDeposit;
emit MinDepositUpdated(oldMinDeposit, newMinDeposit);
}
// change the maximum deposit
function setMaxDeposit(uint newMaxDeposit) public managementOnly {
uint oldMaxDeposit = maximumDeposit;
maximumDeposit = newMaxDeposit;
emit MaxDepositUpdated(oldMaxDeposit, newMaxDeposit);
}
// change the minimum burn rate to acquire a slot
function setMinBurnRate(uint newMinBurnRate) public managementOnly {
uint oldMinBurnRate = minimumBurnRate;
minimumBurnRate = newMinBurnRate;
emit MinBurnRateUpdated(oldMinBurnRate, newMinBurnRate);
}
// change the length of a pulse, should be done with care, probably should update all slots simultaneously
function setPulseWavelength(uint newWavelength) public managementOnly {
uint oldWavelength = pulseWavelengthBlocks;
pulseWavelengthBlocks = newWavelength;
pulseConstant = pulseAmplitudeFVT / pulseWavelengthBlocks.times(pulseWavelengthBlocks);
pulseIntegral = pulseSum(newWavelength);
emit WavelengthUpdated(oldWavelength, newWavelength);
}
// change the maximum height of the reward curve
function setPulseAmplitude(uint newAmplitude) public managementOnly {
uint oldAmplitude = pulseAmplitudeFVT;
pulseAmplitudeFVT = newAmplitude;
pulseConstant = pulseAmplitudeFVT / pulseWavelengthBlocks.times(pulseWavelengthBlocks);
pulseIntegral = pulseSum(pulseWavelengthBlocks);
emit AmplitudeUpdated(oldAmplitude, newAmplitude);
}
// compute the sum of the rewards per pulse
function pulseSum(uint wavelength) public view returns (uint) {
// sum of squares formula
return pulseConstant.times(wavelength.times(wavelength.plus(1))).times(wavelength.times(2).plus(1)) / 6;
}
// compute the undistributed rewards for a slot
function getRewards(uint slotId) public view returns (uint) {
Slot storage slot = slots[slotId];
if (slot.owner == address(0)) {
return 0;
}
uint referenceBlock = block.number;
if (paused) {
referenceBlock = pausedBlock;
}
// three parts, incomplete beginning, incomplete end and complete middle
uint rewards;
// complete middle
// trim off overhang on both ends
uint startPhase = slot.lastUpdatedBlock.minus(pulseStartBlock) % pulseWavelengthBlocks;
uint startOverhang = pulseWavelengthBlocks.minus(startPhase);
uint startSum = pulseSum(startOverhang);
uint blocksDiffTotal = referenceBlock.minus(slot.lastUpdatedBlock);
uint endPhase = referenceBlock.minus(pulseStartBlock) % pulseWavelengthBlocks;
uint endingBlocks = pulseWavelengthBlocks.minus(endPhase);
uint leftoverSum = pulseSum(endingBlocks);
// if we haven't made it to phase 0 yet
if (blocksDiffTotal < startOverhang) {
rewards = startSum.minus(leftoverSum);
} else {
uint blocksDiff = blocksDiffTotal.minus(endPhase).minus(startOverhang);
uint wavelengths = blocksDiff / pulseWavelengthBlocks;
rewards = wavelengths.times(pulseIntegral);
// incomplete beginning of reward cycle, end of pulse
if (startPhase > 0) {
rewards = rewards.plus(pulseSum(startOverhang));
}
// incomplete ending of reward cycle, beginning of pulse
if (endPhase > 0) {
rewards = rewards.plus(pulseIntegral.minus(leftoverSum));
}
}
return rewards;
}
// compute the unapplied burn to the deposit
function getBurn(uint slotId) public view returns (uint) {
Slot storage slot = slots[slotId];
uint referenceBlock = block.number;
if (paused) {
referenceBlock = pausedBlock;
}
uint burn = slot.burnRate * (referenceBlock - slot.lastUpdatedBlock);
if (burn > slot.deposit) {
burn = slot.deposit;
}
return burn;
}
// this must be idempotent, it syncs both the rewards and the deposit burn atomically, and updates lastUpdatedBlock
function updateSlot(uint slotId) public {
Slot storage slot = slots[slotId];
// burn and rewards always have to update together, since they both depend on lastUpdatedBlock
uint burn = getBurn(slotId);
uint rewards = getRewards(slotId);
// update this first to make burn and reward zero in the case of re-entrance
slot.lastUpdatedBlock = block.number;
if (burn > 0) {
// adjust deposit first
slot.deposit = slot.deposit.minus(burn);
// bookkeeping
totalBurned = totalBurned.plus(burn);
totalBurnedFor[slot.owner] = totalBurnedFor[slot.owner].plus(burn);
// burn them!
liquidityToken.transfer(taxAddress, burn);
}
if (rewards > 0) {
// bookkeeping
totalRewards = totalRewards.plus(rewards);
totalRewardsFor[slot.owner] = totalStakedFor[slot.owner].plus(rewards);
rewardsForSession[slotId] = rewardsForSession[slotId].plus(rewards);
rewardToken.transfer(slot.owner, rewards);
}
}
// most important function for users, allows them to start receiving rewards
function claimSlot(uint slotId, uint newBurnRate, uint deposit) external {
require(slotId > 0, 'Slot id must be positive');
require(slotId <= maxStakers, 'Slot id out of range');
require(newBurnRate >= minimumBurnRate, 'Burn rate must meet or exceed minimum');
require(deposit >= minimumDeposit, 'Deposit must meet or exceed minimum');
require(deposit <= maximumDeposit, 'Deposit must not exceed maximum');
require(paused == false, 'Must be unpaused');
Slot storage slot = slots[slotId];
// count the stakers
if (slot.owner == address(0)) {
// assign id since this may be the first time
slot.id = slotId;
numStakers = numStakers.plus(1);
slot.lastUpdatedBlock = block.number;
} else {
updateSlot(slotId);
bool betterDeal = newBurnRate > slot.burnRate && (deposit > slot.deposit || deposit == maximumDeposit);
require(betterDeal || slot.deposit == 0, 'You must outbid the current owner');
// bookkeeping
totalStaked = totalStaked.minus(slot.deposit);
totalStakedFor[slot.owner] = totalStakedFor[slot.owner].minus(slot.deposit);
// withdraw current owner
withdrawFromSlotInternal(slotId);
}
// set new owner, burn rate
slot.owner = msg.sender;
slot.burnRate = newBurnRate;
slot.deposit = deposit;
// bookkeeping
totalStaked = totalStaked.plus(deposit);
totalStakedFor[msg.sender] = totalStakedFor[msg.sender].plus(deposit);
// transfer the tokens!
if (deposit > 0) {
liquidityToken.transferFrom(msg.sender, address(this), deposit);
}
emit SlotChangedHands(slotId, deposit, newBurnRate, msg.sender);
}
// separates user from slot, if either voluntary or delinquent
function withdrawFromSlot(uint slotId) external {
Slot storage slot = slots[slotId];
bool withdrawable = slot.owner == msg.sender || slot.deposit == 0;
require(withdrawable || paused, 'Only owner can call this unless user is delinquent or contract is paused');
updateSlot(slotId);
withdrawFromSlotInternal(slotId);
// zero out owner and burn rate
slot.owner = address(0);
slot.burnRate = 0;
numStakers = numStakers.minus(1);
emit SlotChangedHands(slotId, 0, 0, address(0));
}
// internal function for withdrawing from a slot
function withdrawFromSlotInternal(uint slotId) internal {
Slot storage slot = slots[slotId];
rewardsForSession[slotId] = 0;
// if there's any deposit left,
if (slot.deposit > 0) {
uint deposit = slot.deposit;
slot.deposit = 0;
liquidityToken.transfer(slot.owner, deposit);
}
}
}
|
this must be idempotent, it syncs both the rewards and the deposit burn atomically, and updates lastUpdatedBlock burn and rewards always have to update together, since they both depend on lastUpdatedBlock update this first to make burn and reward zero in the case of re-entrance adjust deposit first bookkeeping burn them! bookkeeping
|
function updateSlot(uint slotId) public {
Slot storage slot = slots[slotId];
uint burn = getBurn(slotId);
uint rewards = getRewards(slotId);
slot.lastUpdatedBlock = block.number;
if (burn > 0) {
slot.deposit = slot.deposit.minus(burn);
totalBurned = totalBurned.plus(burn);
totalBurnedFor[slot.owner] = totalBurnedFor[slot.owner].plus(burn);
liquidityToken.transfer(taxAddress, burn);
}
if (rewards > 0) {
totalRewards = totalRewards.plus(rewards);
totalRewardsFor[slot.owner] = totalStakedFor[slot.owner].plus(rewards);
rewardsForSession[slotId] = rewardsForSession[slotId].plus(rewards);
rewardToken.transfer(slot.owner, rewards);
}
}
| 10,945,787
|
//Address: 0x3080630ecdedb43dec42f19bed68965a45414902
//Contract name: EtheremonSwap
//Balance: 0 Ether
//Verification Date: 2/6/2018
//Transacion Count: 6
// CODE STARTS HERE
// Welcome to the source code of the unofficial Etheremon Swap smart contract! This allows MonSeekers to trustlessly trade mons with each other.
// You can offer up any specific Etheremon you own in exchange for any other specific mon or any mon of a specific class.
// For example, you can offer up your Berrball in exchange for any Dracobra.
// Or you can offer it in exchange for some specific mon specified by object ID, like that level 50 Pangrass named "Donny".
// You can even keep both offers up at once if you want.
// If someone has an offer up that your mon qualifies for (for example if "Donny" belongs to you or you happen to own a Dracobra), you can match that offer to execute the trade, instantly transferring the mons to their new owners.
pragma solidity ^0.4.19;
contract Ownable
{
address public owner;
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
function Ownable() public
{
owner = msg.sender;
}
}
// Interface for the official Etheremon Data contract.
contract EtheremonData
{
function getMonsterObj(uint64 _objId) constant public returns(uint64 objId, uint32 classId, address trainer, uint32 exp, uint32 createIndex, uint32 lastClaimIndex, uint createTime);
}
// Interface for the official Etheremon Trade contract.
contract EtheremonTrade
{
function freeTransferItem(uint64 _objId, address _receiver) external;
}
// Deposit contract. Each trader has a unique one which is generated ONCE and never changes.
// To trade a mon, it must be deposited in your deposit address. You can't trade mons that aren't deposited!
// Each trader has complete control over mons in their deposit address, so only send YOUR mons to YOUR unique deposit address!
// Sending a mon to someone else's deposit address is the same as giving them the mon for free.
// Finally, make sure you actually GENERATE a deposit address before depositing mons.
// If you haven't generated one before then your deposit address will appear to be 0x000... which is NOT A REAL DEPOSIT ADDRESS! Any mons sent to 0x000... will be lost forever!
contract EtheremonDepositContract is Ownable
{
function sendMon(address tradeAddress, address receiver, uint64 mon) external onlyOwner // The "owner" is always the EtheremonSwap contract itself because it created this deposit contract on your behalf.
{
EtheremonTrade(tradeAddress).freeTransferItem(mon, receiver);
}
}
// This is the main contract. This needs an owner (it's me, hi!) because it is possible for Etheremon's Trade contract to be upgraded. The owner of this contract is responsible for updating the Trade address if/when that happens.
// Eventually Etheremon will be fully decentralized and we can be sure the Trade contract will never be changed. After that happens the owner of THIS contract will be set to 0x0, effectively revoking ownership.
// The only power the contract owner has is changing the address pointing to the official Etheremon Trade contract.
// If the contract owner is compromised, the worst that could happen is you will no longer be able to trade mons through this contract.
// It is NOT possible for the contract owner to withdraw anyone else's mons.
// It is NOT possible for the contract owner to sever the link between a user and their deposit address.
// It is NOT possible for the contract owner to prevent a user from withdrawing their deposited mons.
// Even if the contract owner tried to set up his own malicious copy of the Trade contract, only the official Etheremon Trade contract has the authority to transfer mons, so nothing could be accomplished that way.
contract EtheremonSwap is Ownable
{
address public dataAddress = 0xabc1c404424bdf24c19a5cc5ef8f47781d18eb3e;
address public tradeAddress = 0x4ba72f0f8dad13709ee28a992869e79d0fe47030;
mapping(address => address) public depositAddress;
mapping(uint64 => address) public monToTrainer; // Only valid for POSTED mons.
mapping(uint64 => uint64) public listedMonForMon;
mapping(uint64 => uint32) public listedMonForClass;
// Included here instead of Ownable because the Deposit contracts don't need it.
function changeOwner(address newOwner) onlyOwner external
{
owner = newOwner;
}
function setTradeAddress(address _tradeAddress) onlyOwner external
{
tradeAddress = _tradeAddress;
}
// Generates a new deposit address for the sender.
function generateDepositAddress() external
{
require(depositAddress[msg.sender] == 0); // Any given address may only have one deposit address at a time.
depositAddress[msg.sender] = new EtheremonDepositContract();
}
// Withdraws the given mon from your deposit address. Only reason to do this is if someone changed their mind about trading a mon.
function withdrawMon(uint64 mon) external
{
// Only possible to withdraw if you have a deposit address in the first place.
require(depositAddress[msg.sender] != 0);
// Delist the mon from any posted trades.
delist(mon);
// Execute the withdrawal. No need to check ownership or anything; Etheremon's official trade contract will revert this transaction for us if there's a problem.
EtheremonDepositContract(depositAddress[msg.sender]).sendMon(tradeAddress, msg.sender, mon);
}
// If the contract owner is compromised or has failed to update the reference to the Trade contract after an Etheremon upgrade,
// you can use this function to withdraw any deposited mons by providing the address of the official Etheremon Trade contract.
function emergencyWithdraw(address _tradeAddress, uint64 mon) external
{
// Exactly the same as the regular withdrawal but with a user-provided trade address.
require(depositAddress[msg.sender] != 0);
delist(mon);
EtheremonDepositContract(depositAddress[msg.sender]).sendMon(_tradeAddress, msg.sender, mon);
}
// Posts a trade offering up your mon for ONLY the given mon.
// Will replace this mon's currently listed Mon-for-Mon trade if it exists.
// Will NOT replace this mon's currently listed Mon-for-Class trade if it exists!
function postMonForMon(uint64 yourMon, uint64 desiredMon) external
{
// Make sure you own and have deposited the mon you're posting.
checkOwnership(yourMon);
// Make sure you're requesting a valid mon.
require(desiredMon != 0);
listedMonForMon[yourMon] = desiredMon;
monToTrainer[yourMon] = msg.sender;
}
// Posts a trade offering up your mon for ANY mon of the given class.
// To figure out the class ID, just look at the URL of that mon's page.
// For example, Tygloo is class 33: https://www.etheremon.com/#/mons/33
// Will replace this mon's currently listed Mon-for-Class trade if it exists.
// Will NOT replace this mon's currently listed Mon-for-Mon trade if it exists!
function postMonForClass(uint64 yourMon, uint32 desiredClass) external
{
// Make sure you own and have deposited the mon you're posting.
checkOwnership(yourMon);
// Make sure you're requesting a valid class.
require(desiredClass != 0);
listedMonForClass[yourMon] = desiredClass;
monToTrainer[yourMon] = msg.sender;
}
// Delists the given mon from all posted trades. This is only useful if you still want to trade it later.
// If you just want to modify your listing, use appropriate the postMon functions instead.
// If you just want your mon back, use withdrawMon. Withdrawn mons get delisted automatically.
function delistMon(uint64 mon) external
{
// Make sure the mon is both listed and owned by the sender.
require(monToTrainer[mon] == msg.sender);
delist(mon);
}
// Matches a posted trade.
function trade(uint64 yourMon, uint64 desiredMon) external
{
// No need to waste gas checking for weird uncommon situations (like yourMon and desiredMon being owned by
// the same address or even being the same mon) because the trade will revert in those situations anyway.
// Make sure you own and have deposited the mon you're offering.
checkOwnership(yourMon);
// If there's no exact match...
if(listedMonForMon[desiredMon] != yourMon)
{
// ...check for a class match.
uint32 class;
(,class,,,,,) = EtheremonData(dataAddress).getMonsterObj(yourMon);
require(listedMonForClass[desiredMon] == class);
}
// If we reached this point, we have a match. Now we execute the trade.
executeTrade(msg.sender, yourMon, monToTrainer[desiredMon], desiredMon);
// The trade was successful. Delist all mons involved.
delist(yourMon);
delist(desiredMon);
}
// Ensures the sender owns and has deposited the given mon.
function checkOwnership(uint64 mon) private view
{
require(depositAddress[msg.sender] != 0); // Obviously you must have a deposit address in the first place.
address trainer;
(,,trainer,,,,) = EtheremonData(dataAddress).getMonsterObj(mon);
require(trainer == depositAddress[msg.sender]);
}
// Executes a trade, swapping the mons between trainer A and trainer B.
// No withdrawal is necessary: the mons end up in the trainers' actual addresses, NOT their deposit addresses!
function executeTrade(address trainerA, uint64 monA, address trainerB, uint64 monB) private
{
EtheremonDepositContract(depositAddress[trainerA]).sendMon(tradeAddress, trainerB, monA); // Mon A from trainer A to trainer B.
EtheremonDepositContract(depositAddress[trainerB]).sendMon(tradeAddress, trainerA, monB); // Mon B from trainer B to trainer A.
}
// Delists the given mon from any posted trades.
function delist(uint64 mon) private
{
if(listedMonForMon [mon] != 0){listedMonForMon [mon] = 0;}
if(listedMonForClass[mon] != 0){listedMonForClass[mon] = 0;}
if(monToTrainer [mon] != 0){monToTrainer [mon] = 0;}
}
}
|
Withdraws the given mon from your deposit address. Only reason to do this is if someone changed their mind about trading a mon. Only possible to withdraw if you have a deposit address in the first place. Delist the mon from any posted trades. Execute the withdrawal. No need to check ownership or anything; Etheremon's official trade contract will revert this transaction for us if there's a problem.
|
function withdrawMon(uint64 mon) external
{
require(depositAddress[msg.sender] != 0);
delist(mon);
EtheremonDepositContract(depositAddress[msg.sender]).sendMon(tradeAddress, msg.sender, mon);
}
| 5,480,509
|
./partial_match/1/0x84335C12b44Df24ec5B5Baa242BCD645941c0609/sources/ApprovalHolder.sol
|
remove invoker _previousInvoker The invoker address to be removed/
|
function removeInvoker(address _previousInvoker) public {
require(msg.sender == admin, "not admin");
require(isInvoker[_previousInvoker] == true, "address is not an invoker");
isInvoker[_previousInvoker] = false;
emit InvokerRemoved(_previousInvoker);
}
| 3,547,695
|
//Address: 0xbac2dc4fe58f1f3382f036b1cb8d92591e0c135f
//Contract name: MiningToken
//Balance: 8 wei
//Verification Date: 3/2/2018
//Transacion Count: 19
// CODE STARTS HERE
pragma solidity ^0.4.16;
// The following is the Ethereum Mining Manager Contract, Version Two.
// It assumes that each graphics card draws 80 watts (75 watts for gtx 1050 ti and 5 watts for 1/13 of the rig, an underestimate)
// It also assumes that the cost of electricity is .20$/KWh
// Tokens can only be tranferred by their owners.
// Tokens(Graphics Cards) can be created to and destroyed from anyone if done by the Contract creator.
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
//mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
//require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
//allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
/******************************************/
/* MINING CONTRACT MAIN CODE */
/******************************************/
contract MiningToken is owned, TokenERC20 {
uint256 public supplyReady; // How many are in stock to be bought (set to zero to disable the buying of cards)
uint256 public min4payout; // Minimum ether in contract for payout to be allowed
uint256 public centsPerMonth;// Cost to run a card
mapping(uint256 => address) public holders; // Contract's list of people who own graphics cards
mapping(address => uint256) public indexes;
uint256 public num_holders=1;
/* Initializes contract with initial supply tokens to the creator of the contract */
function MiningToken(
string tokenName,
string tokenSymbol
) TokenERC20(0, tokenName, tokenSymbol) public {
centsPerMonth=0;
decimals=0;
setMinimum(0);
holders[num_holders++]=(msg.sender);
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
if(indexes[_to]==0||holders[indexes[_to]]==0){
indexes[_to]=num_holders;
holders[num_holders++]=_to;
}
Transfer(_from, _to, _value);
}
// Set minimum payout
function setMinimum(uint256 d) onlyOwner public{
min4payout=d*1 ether / 1000;
}
// set card $/watt/month
function setCentsPerMonth(uint256 amount) onlyOwner public {
centsPerMonth=amount;
}
// get mining payout and send to everyone
// Requires price of ethereum to deduct electricity cost
function getPayout(uint etherPrice) onlyOwner public {
require(this.balance>min4payout);
uint256 perToken=this.balance/totalSupply;
for (uint i = 1; i < num_holders; i++) {
address d=holders[i];
if(d!=0){
uint bal=balanceOf[d];
if(bal==0){
holders[i]=0;
}else{
uint powercost=((bal*centsPerMonth)/100) *( 1 ether/etherPrice);
holders[i].transfer((bal * perToken)-powercost);
}
}
}
owner.transfer(((totalSupply*centsPerMonth)/100) *( 1 ether/etherPrice)); // transfer elecricity cost to contract owner
}
// add graphics card for owner of contract
function mint(uint256 amt) onlyOwner public {
balanceOf[owner] += amt;
totalSupply += amt;
Transfer(this, msg.sender, amt);
}
// add graphics cards for someone else
function mintTo(uint256 amt,address to) onlyOwner public {
balanceOf[to] += amt;
totalSupply += amt;
Transfer(this, to, amt);
if(indexes[to]==0||holders[indexes[to]]==0){
indexes[to]=num_holders;
holders[num_holders++]=to;
}
}
// cards cannot be sold unless the contract is destroyed
/// notice Sell `amount` tokens to contract
/// param amount amount of tokens to be sold
//function sell(uint256 amount) public {
// require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
// burnFrom(msg.sender, amount); // makes the transfers
// msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
//}
// allows contract to be paid:
function() payable public{
}
// If something goes wrong we can destroy the contract and everyone gets a refund at card price for each of their cards.
// by setting the price of cards to zero then no refund is sent.
// if a refund is executed then the contract first must have enough Ether to do the refund.
// Send the Ethereum to the contract as necessary first.
function selfDestruct() onlyOwner payable public{
uint256 perToken=this.balance/totalSupply;
for (uint i = 1; i < num_holders; i++) {
holders[i].transfer(balanceOf[holders[i]] * perToken);
}
// pay the rest to the owner
selfdestruct(owner);
}
}
|
add graphics card for owner of contract
|
function mint(uint256 amt) onlyOwner public {
balanceOf[owner] += amt;
totalSupply += amt;
Transfer(this, msg.sender, amt);
}
| 5,521,406
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/vigilance91/solidarity/libraries/address/AddressConstraints.sol";
import "https://github.com/vigilance91/solidarity/ERC/introspection/ERC165/frameworkERC165.sol";
import "https://github.com/vigilance91/solidarity/contracts/token/ERC20/iERC20Receiver.sol";
///
/// @title framework for ERC20 Safe Transfer Introspection
/// @author Tyler R. Drury <vigilstudios.td@gmail.com> (www.twitter.com/StudiosVigil) - copyright 18/4/2021, All Rights Reserved
///
library frameworkSafeERC20
{
using LogicConstraints for bool;
using AddressConstraints for address;
using Address for address;
using frameworkERC165 for address;
//using frameworkERC173 for address;
//string private constant _NAME = ' frameworkSafeERC20: ';
bytes private constant _ERC20_RECEIVE_SIGNATURE = abi.encodeWithSignature('canReceiveERC20()');
bytes4 private constant _iERC20_RECEIVER_ID = type(iERC20Receiver).interfaceId;
bytes4 internal constant _ERC20_RECEIVED = iERC20Receiver.onERC20Received.selector;
function _requireSupportsInterface(
address target
)private view
{
target.supportsInterface(_iERC20_RECEIVER_ID).requireTrue(
'contract does not implement iERC20Receiver'
);
}
function canReceiveERC20(
address target
)internal view returns(
bool ret
){
target.requireNotNull(
);
if(!target.isContract()){
return true;
}
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
_ERC20_RECEIVE_SIGNATURE
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool));
}
function onERC20Received(
address recipient,
address from,
uint256 amount
)internal returns(
bool
){
recipient.requireNotNull();
if(!recipient.isContract()){
return true;
}
_requireSupportsInterface(recipient);
(bool success, bytes memory result) = recipient.call(
abi.encodeWithSignature(
'onERC20Received(address,uint256)',
from,
amount
)
);
success.requireTrue('onERC20Received: call failed');
(bytes4 retval) = abi.decode(result, (bytes4));
return (retval == _ERC20_RECEIVED);
}
/**
//transfer `amount` of tokens from this contract to Owner
function safeTransferToOwner(
address target,
uint256 amount
)internal returns(
bool
){
//target.supportsInterface(_iERC173_ID).requireTrue(
//'contract does not implement ERC173'
//);
address O = target.owner();
_requireCanReceiveERC20(O);
target.transfer(
address(this),
O,
amount
);
return true;
}
*/
}
|
transfer `amount` of tokens from this contract to Ownertarget.supportsInterface(_iERC173_ID).requireTrue('contract does not implement ERC173');
|
function safeTransferToOwner(
address target,
uint256 amount
)internal returns(
bool
){
address O = target.owner();
_requireCanReceiveERC20(O);
target.transfer(
address(this),
O,
amount
);
return true;
}
| 12,677,867
|
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: contracts/IETradingNFT.sol
pragma solidity 0.6.12;
interface IETradingNFT {
function mint(address _to, uint256 _id, uint256 _quantity, bytes memory _data) external ;
function totalSupply(uint256 _id) external view returns (uint256);
function maxSupply(uint256 _id) external view returns (uint256);
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
}
// File: contracts/token/interfaces/IERC20Token.sol
pragma solidity 0.6.12;
/*
ERC20 Standard Token interface
*/
interface IERC20Token {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function eulerBalances(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
}
// File: contracts/token/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
_notThis(_address);
_;
}
// error message binary size optimization
function _notThis(address _address) internal view {
require(_address != address(this), "ERR_ADDRESS_IS_SELF");
}
}
// File: contracts/token/ERC20Token.sol
pragma solidity 0.6.12;
/**
* @dev ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
using SafeMath for uint256;
string public override name;
string public override symbol;
uint8 public override decimals;
uint256 public override totalSupply;
mapping (address => uint256) public override eulerBalances;
mapping (address => mapping (address => uint256)) public override allowance;
/**
* @dev triggered when tokens are transferred between wallets
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf
*
* @param _owner wallet that approves the allowance
* @param _spender wallet that receives the allowance
* @param _value allowance amount
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _totalSupply total supply of token units
*/
constructor(string memory _name, string memory _symbol, uint256 _totalSupply) public {
// validate input
require(bytes(_name).length > 0, "ERR_INVALID_NAME");
require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL");
name = _name;
symbol = _symbol;
decimals = 18;
totalSupply = _totalSupply;
eulerBalances[msg.sender] = _totalSupply;
}
/**
* @dev transfers tokens to a given address
* throws on any error rather then return a false flag to minimize user errors
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
virtual
override
validAddress(_to)
returns (bool)
{
eulerBalances[msg.sender] = eulerBalances[msg.sender].sub(_value);
eulerBalances[_to] = eulerBalances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev transfers tokens to a given address on behalf of another address
* throws on any error rather then return a false flag to minimize user errors
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
virtual
override
validAddress(_from)
validAddress(_to)
returns (bool)
{
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
eulerBalances[_from] = eulerBalances[_from].sub(_value);
eulerBalances[_to] = eulerBalances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev allows another account/contract to transfers tokens on behalf of the caller
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
virtual
override
validAddress(_spender)
returns (bool)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0, "ERR_INVALID_AMOUNT");
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
// File: contracts/token/utility/interfaces/IOwned.sol
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: contracts/token/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) external;
}
// File: contracts/token/utility/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned, ITokenHolder {
}
// File: contracts/token/interfaces/IEulerToken.sol
pragma solidity 0.6.12;
/*
Euler Token interface
*/
interface IEulerToken is IConverterAnchor, IERC20Token {
function disableTransfers(bool _disable) external;
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: contracts/token/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier onlyOwner {
_onlyOwner();
_;
}
// error message binary size optimization
function _onlyOwner() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @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 OwnerUpdate(owner, address(0));
owner = address(0);
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override onlyOwner {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() override public {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: contracts/token/utility/TokenHandler.sol
pragma solidity 0.6.12;
contract TokenHandler {
bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)"));
bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)"));
/**
* @dev executes the ERC20 token's `approve` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _spender approved address
* @param _value allowance amount
*/
function safeApprove(IERC20Token _token, address _spender, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_APPROVE_FAILED');
}
/**
* @dev executes the ERC20 token's `transfer` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _to target address
* @param _value transfer amount
*/
function safeTransfer(IERC20Token _token, address _to, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FAILED');
}
/**
* @dev executes the ERC20 token's `transferFrom` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
function safeTransferFrom(IERC20Token _token, address _from, address _to, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FROM_FAILED');
}
}
// File: contracts/token/utility/TokenHolder.sol
pragma solidity 0.6.12;
/**
* @dev We consider every contract to be a 'token holder' since it's currently not possible
* for a contract to deny receiving tokens.
*
* The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
* the owner to send tokens that were sent to the contract by mistake back to their sender.
*
* Note that we use the non standard ERC-20 interface which has no return value for transfer
* in order to support both non standard as well as standard token contracts.
* see https://github.com/ethereum/solidity/issues/4116
*/
contract TokenHolder is ITokenHolder, TokenHandler, Owned, Utils {
/**
* @dev withdraws tokens held by the contract and sends them to an account
* can only be called by the owner
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
virtual
override
onlyOwner
validAddress(address(_token))
validAddress(_to)
{
safeTransfer(_token, _to, _amount);
}
}
// File: contracts/token/EulerToken.sol
pragma solidity 0.6.12;
/**
* @dev Euler Token
*
* 'Owned' is specified here for readability reasons
*/
contract EulerToken is IEulerToken, Owned, ERC20Token, TokenHolder {
using SafeMath for uint256;
bool public transfersEnabled = false; // true if transfer/transferFrom are enabled, false otherwise
/**
* @dev triggered when the total supply is increased
*
* @param _amount amount that gets added to the supply
*/
event Issuance(uint256 _amount);
/**
* @dev triggered when the total supply is decreased
*
* @param _amount amount that gets removed from the supply
*/
event Destruction(uint256 _amount);
/**
* @dev initializes a new EulerToken instance
*
* @param _name token name
* @param _symbol token short symbol, minimum 1 character
*/
constructor(string memory _name, string memory _symbol)
public
ERC20Token(_name, _symbol, 0)
{
}
// allows execution only when transfers are enabled
modifier transfersAllowed {
_transfersAllowed();
_;
}
// error message binary size optimization
function _transfersAllowed() internal view {
require(transfersEnabled, "ERR_TRANSFERS_DISABLED");
}
/**
* @dev disables/enables transfers
* can only be called by the contract owner
*
* @param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public override onlyOwner {
transfersEnabled = !_disable;
}
/**
* @dev increases the token supply and sends the new tokens to the given account
* can only be called by the contract owner
*
* @param _to account to receive the new amount
* @param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
override
onlyOwner
validAddress(_to)
{
totalSupply = totalSupply.add(_amount);
eulerBalances[_to] = eulerBalances[_to].add(_amount);
emit Issuance(_amount);
emit Transfer(address(0), _to, _amount);
}
/**
* @dev removes tokens from the given account and decreases the token supply
* can only be called by the contract owner
*
* @param _from account to remove the amount from
* @param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public override onlyOwner {
eulerBalances[_from] = eulerBalances[_from].sub(_amount);
totalSupply = totalSupply.sub(_amount);
emit Transfer(_from, address(0), _amount);
emit Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
* @dev send coins
* throws on any error rather then return a false flag to minimize user errors
* in addition to the standard checks, the function throws if transfers are disabled
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
override(IERC20Token, ERC20Token)
transfersAllowed
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev an account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
* in addition to the standard checks, the function throws if transfers are disabled
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
override(IERC20Token, ERC20Token)
transfersAllowed
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
}
// File: contracts/EulersFormula.sol
pragma solidity 0.6.12;
interface IMigratorEulersFormula {
// Perform LP token migration from legacy UniswapV2 to ESwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// ESwap must mint EXACTLY the same amount of ESwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
contract Formula is EulerToken("Euler's Formula", "EULER") {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Airdrop list
address[] public airdropList;
// Only deposit user can get airdrop.
mapping(address => bool) addressAvailable;
mapping(address => bool) addressAvailableHistory;
// Claimable enft of user.
struct UserEnftInfo {
uint256 amount;
}
// Info of each user that claimable enft.
mapping (address => mapping (uint256 => UserEnftInfo)) public userEnftInfo;
// Info of each enft.
struct EnftInfo {
uint256 enftID; // Enft's ID.
uint256 amount; // Distribution amount.
uint256 fixedPrice; // Claim the enft need pay some wETH.
}
// Info of each enft.
EnftInfo[] public enftInfo;
// Total enft amount.
uint256 public totalEnftAmount = 0;
// Original total enft amount.
uint256 public originalTotalEnftAmount = 0;
// Draw Fusion
uint256 public eulersFused = 1000 * (10 ** 18);
// Base number
uint256 public base = 10 ** 6;
// Claim fee is 3%.
// Pool's fee 1%. Artist's fee 2%.
uint256 public totalFee = 3 * (base) / 100;
// Enft token.
IETradingNFT ETradingNFT;
event Reward(address indexed user, uint256 indexed enftID);
event AirDrop(address indexed user, uint256 indexed enftID);
function enftLength() public view returns (uint256) {
return enftInfo.length;
}
function eulerBalanceOf(address tokenOwner) public view returns (uint256) {
return eulerBalances[tokenOwner];
}
function userEnftBalanceOf(address tokenOwner, uint256 _enftID) public view returns (uint256) {
return userEnftInfo[tokenOwner][_enftID].amount;
}
function userUnclaimEnft(address tokenOwner) public view returns (uint256[] memory) {
uint256[] memory userEnft = new uint256[](enftInfo.length);
for(uint i = 0; i < enftInfo.length; i++) {
userEnft[i] = userEnftInfo[tokenOwner][i].amount;
}
return userEnft;
}
function enftBalanceOf(uint256 _enftID) public view returns (uint256) {
return enftInfo[_enftID].amount;
}
// Set setEulersFused. Can only be called by the owner.
function setEulersFused(uint256 _newEulersFused) public onlyOwner {
eulersFused = _newEulersFused;
}
// Set setTotalFee. Can only be called by the owner.
function setTotalFee(uint256 _newTotalFee) public onlyOwner {
totalFee = _newTotalFee;
}
// Add a new enft. Can only be called by the owner.
function addEnft(uint256 _enftID, uint256 _amount, uint256 _fixedPrice) external onlyOwner {
require(_amount.add(ETradingNFT.totalSupply(_enftID)) <= ETradingNFT.maxSupply(_enftID), "Max supply reached");
totalEnftAmount = totalEnftAmount.add(_amount);
originalTotalEnftAmount = originalTotalEnftAmount.add(_amount);
enftInfo.push(EnftInfo({
enftID: _enftID,
amount: _amount,
fixedPrice: _fixedPrice
}));
}
// Update enft.
// It's always decrease.
function _updateEnft(uint256 _wid, uint256 amount) internal {
EnftInfo storage enft = enftInfo[_wid];
enft.amount = enft.amount.sub(amount);
totalEnftAmount = totalEnftAmount.sub(amount);
}
// Update user enft
function _addUserEnft(address user, uint256 _wid, uint256 amount) internal {
UserEnftInfo storage userEnft = userEnftInfo[user][_wid];
userEnft.amount = userEnft.amount.add(amount);
}
function _removeUserEnft(address user, uint256 _wid, uint256 amount) internal {
UserEnftInfo storage userEnft = userEnftInfo[user][_wid];
userEnft.amount = userEnft.amount.sub(amount);
}
// Draw main function
function _draw() internal view returns (uint256) {
uint256 seed = uint256(keccak256(abi.encodePacked(now, block.difficulty, msg.sender)));
uint256 rnd = UniformRandomNumber.uniform(seed, totalEnftAmount);
// Sort by rarity. Avoid gas attacks, start from the tail.
for(uint i = enftInfo.length - 1; i > 0; --i){
if(rnd < enftInfo[i].amount){
return i;
}
rnd = rnd - enftInfo[i].amount;
}
// should not happen.
return uint256(-1);
}
// Draw a enft
function draw() external {
// EOA only
require(msg.sender == tx.origin);
require(eulerBalances[msg.sender] >= eulersFused, "Eulers are not enough.");
eulerBalances[msg.sender] = eulerBalances[msg.sender].sub(eulersFused);
uint256 _rwid = _draw();
// Reward reduced
_updateEnft(_rwid, 1);
_addUserEnft(msg.sender, _rwid, 1);
emit Reward(msg.sender, _rwid);
}
// Airdrop by owner
function airDrop() external onlyOwner {
uint256 _rwid = _draw();
// Reward reduced
_updateEnft(_rwid, 1);
uint256 seed = uint256(keccak256(abi.encodePacked(now, _rwid)));
bool status = false;
uint256 rnd = 0;
while (!status) {
rnd = UniformRandomNumber.uniform(seed, airdropList.length);
status = addressAvailable[airdropList[rnd]];
seed = uint256(keccak256(abi.encodePacked(seed, rnd)));
}
_addUserEnft(airdropList[rnd], _rwid, 1);
emit AirDrop(airdropList[rnd], _rwid);
}
// Airdrop by user
function airDropByUser() external {
// EOA only
require(msg.sender == tx.origin);
require(eulerBalances[msg.sender] >= eulersFused, "Eulers are not enough.");
eulerBalances[msg.sender] = eulerBalances[msg.sender].sub(eulersFused);
uint256 _rwid = _draw();
// Reward reduced
_updateEnft(_rwid, 1);
uint256 seed = uint256(keccak256(abi.encodePacked(now, _rwid)));
bool status = false;
uint256 rnd = 0;
while (!status) {
rnd = UniformRandomNumber.uniform(seed, airdropList.length);
status = addressAvailable[airdropList[rnd]];
seed = uint256(keccak256(abi.encodePacked(seed, rnd)));
}
_addUserEnft(airdropList[rnd], _rwid, 1);
emit AirDrop(airdropList[rnd], _rwid);
}
// pool's fee & artist's fee
function withdrawFee() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
// Compute claim fee.
function claimFee(uint256 _wid, uint256 amount) public view returns (uint256){
EnftInfo storage enft = enftInfo[_wid];
return amount * enft.fixedPrice * (totalFee) / (base);
}
// User claim enft.
function claim(uint256 _wid, uint256 amount) external payable {
UserEnftInfo storage userEnft = userEnftInfo[msg.sender][_wid];
require(amount > 0, "amount must not zero");
require(userEnft.amount >= amount, "amount is bad");
require(msg.value == claimFee(_wid, amount), "need payout claim fee");
_removeUserEnft(msg.sender, _wid, amount);
ETradingNFT.mint(msg.sender, _wid, amount, "");
}
}
contract EulersFormula is Formula {
// Info of each user.
struct UserLPInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardEULER; // Reward euler.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. EULERs to distribute per block.
uint256 lastRewardBlock; // Last block number that EULERs distribution occurs.
uint256 accEULERPerShare; // Accumulated EULERs per share, times 1e12. See below.
}
// Dev address.
address public devaddr;
// Block number when bonus EARN period ends.
uint256 public bonusEndBlock;
// EULER tokens created per block.
uint256 public eulerPerBlock = 3141592653589793238; //18 decimals
// Bonus muliplier for early euler seekers.
uint256 public bonusMultiplier = 2718281828459045235; //18 decimals
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorEulersFormula public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserLPInfo)) public userLPInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when EULER mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
IETradingNFT _ETradingNFT,
address _devaddr,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
ETradingNFT = _ETradingNFT;
devaddr = _devaddr;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
enftInfo.push(EnftInfo({
enftID: 0,
amount: 0,
fixedPrice: 0
}));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEULERPerShare: 0
}));
}
// Update the given pool's Eulers allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set eulerPerBlock. Can only be called by the owner.
function setEULERPerBlock(uint256 _eulerPerBlock) public onlyOwner {
eulerPerBlock = _eulerPerBlock;
}
// Set startBlock. Can only be called by the owner.
function setStartBlock(uint256 _startBlock) public onlyOwner {
startBlock = _startBlock;
}
// Set bonusEndBlock. Can only be called by the owner.
function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
// Set bonusMultiplier. Can only be called by the owner.
function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
// Set newLpToken. Can only be called by the owner.
function setNewLpToken(uint _pid, IERC20 _newLpToken) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.lpToken = _newLpToken;
}
// Set newAllocPoint. Can only be called by the owner.
function setNewAllocPoint(uint _pid, uint256 _newAllocPoint) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.allocPoint = _newAllocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorEulersFormula _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can only be called by the owner. We trust that migrator contract is good.
function migrate(uint256 _pid) public onlyOwner {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
//check balance equivalence on Migrator side
//require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(bonusMultiplier);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(bonusMultiplier).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending Eulers on frontend.
function pendingEULER(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserLPInfo storage user = userLPInfo[_pid][_user];
uint256 accEULERPerShare = pool.accEULERPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eulerReward = multiplier.mul(eulerPerBlock).mul(pool.allocPoint).div(totalAllocPoint).div(1e18);
accEULERPerShare = accEULERPerShare.add(eulerReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEULERPerShare).div(1e12).sub(user.rewardEULER);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eulerReward = multiplier.mul(eulerPerBlock).mul(pool.allocPoint).div(totalAllocPoint).div(1e18);
issue(devaddr, eulerReward);
issue(address(this), eulerReward);
pool.accEULERPerShare = pool.accEULERPerShare.add(eulerReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to Formula for EULER allocation.
function deposit(uint256 _pid, uint256 _amount) public {
// EOA only
require(msg.sender == tx.origin);
PoolInfo storage pool = poolInfo[_pid];
UserLPInfo storage user = userLPInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEULERPerShare).div(1e12).sub(user.rewardEULER);
if(pending > 0) {
safeEulerTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardEULER = user.amount.mul(pool.accEULERPerShare).div(1e12);
if (user.amount > 0){
addressAvailable[msg.sender] = true;
if(!addressAvailableHistory[msg.sender]){
addressAvailableHistory[msg.sender] = true;
airdropList.push(msg.sender);
}
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from Formula.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserLPInfo storage user = userLPInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEULERPerShare).div(1e12).sub(user.rewardEULER);
if(pending > 0) {
safeEulerTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardEULER = user.amount.mul(pool.accEULERPerShare).div(1e12);
if (user.amount == 0){
addressAvailable[msg.sender] = false;
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserLPInfo storage user = userLPInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardEULER = 0;
addressAvailable[msg.sender] = false;
}
// Safe euler transfer function, just in case if rounding error causes pool to not have enough EULERs.
function safeEulerTransfer(address _to, uint256 _amount) internal {
uint256 eulerBal = eulerBalanceOf(address(this));
if (_amount > eulerBal) {
transfer(_to, eulerBal);
} else {
transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Set bonusMultiplier. Can only be called by the owner.
|
function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
| 7,830,052
|
./partial_match/4/0xf68198B760945c38eCe34630aea53DBC43F86B3d/sources/GenesisPool.sol
|
用户提现分红给用户发送代币用户余额减少合约中储存的代币余额减少发送代币TODO 调用event事件
|
function withDrawBonus() external{
uint256 amount = bonus[msg.sender];
bonus[msg.sender] = 0;
erc20Balance = erc20Balance.sub(amount);
erc20ConctractAddress.transfer(msg.sender, amount);
emit WithdrawnBonus(msg.sender,amount);
}
| 8,678,968
|
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../utility/ContractRegistryClient.sol";
import "../token/interfaces/IDSToken.sol";
import "./interfaces/IConverter.sol";
import "./interfaces/IConverterFactory.sol";
import "./interfaces/IConverterRegistry.sol";
import "./interfaces/IConverterRegistryData.sol";
/**
* @dev This contract maintains a list of all active converters in the Bancor Network.
*
* Since converters can be upgraded and thus their address can change, the registry actually keeps
* converter anchors internally and not the converters themselves.
* The active converter for each anchor can be easily accessed by querying the anchor's owner.
*
* The registry exposes 3 different lists that can be accessed and iterated, based on the use-case of the caller:
* - Anchors - can be used to get all the latest / historical data in the network
* - Liquidity pools - can be used to get all liquidity pools for funding, liquidation etc.
* - Convertible tokens - can be used to get all tokens that can be converted in the network (excluding pool
* tokens), and for each one - all anchors that hold it in their reserves
*
*
* The contract fires events whenever one of the primitives is added to or removed from the registry
*
* The contract is upgradable.
*/
contract ConverterRegistry is IConverterRegistry, ContractRegistryClient {
/**
* @dev triggered when a converter anchor is added to the registry
*
* @param anchor anchor token
*/
event ConverterAnchorAdded(IConverterAnchor indexed anchor);
/**
* @dev triggered when a converter anchor is removed from the registry
*
* @param anchor anchor token
*/
event ConverterAnchorRemoved(IConverterAnchor indexed anchor);
/**
* @dev triggered when a liquidity pool is added to the registry
*
* @param liquidityPool liquidity pool
*/
event LiquidityPoolAdded(IConverterAnchor indexed liquidityPool);
/**
* @dev triggered when a liquidity pool is removed from the registry
*
* @param liquidityPool liquidity pool
*/
event LiquidityPoolRemoved(IConverterAnchor indexed liquidityPool);
/**
* @dev triggered when a convertible token is added to the registry
*
* @param convertibleToken convertible token
* @param smartToken associated anchor token
*/
event ConvertibleTokenAdded(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken);
/**
* @dev triggered when a convertible token is removed from the registry
*
* @param convertibleToken convertible token
* @param smartToken associated anchor token
*/
event ConvertibleTokenRemoved(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken);
/**
* @dev deprecated, backward compatibility, use `ConverterAnchorAdded`
*/
event SmartTokenAdded(IConverterAnchor indexed smartToken);
/**
* @dev deprecated, backward compatibility, use `ConverterAnchorRemoved`
*/
event SmartTokenRemoved(IConverterAnchor indexed smartToken);
/**
* @dev initializes a new ConverterRegistry instance
*
* @param registry address of a contract registry contract
*/
constructor(IContractRegistry registry) public ContractRegistryClient(registry) {}
/**
* @dev creates an empty liquidity pool and adds its converter to the registry
*
* @param converterType converter type
* @param name token / pool name
* @param symbol token / pool symbol
* @param decimals token / pool decimals
* @param maxConversionFee maximum conversion-fee
* @param reserveTokens reserve tokens
* @param reserveWeights reserve weights
*
* @return new converter
*/
function newConverter(
uint16 converterType,
string memory name,
string memory symbol,
uint8 decimals,
uint32 maxConversionFee,
IReserveToken[] memory reserveTokens,
uint32[] memory reserveWeights
) public virtual returns (IConverter) {
uint256 length = reserveTokens.length;
require(length == reserveWeights.length, "ERR_INVALID_RESERVES");
// for standard pools, change type 1 to type 3
if (converterType == 1 && isStandardPool(reserveWeights)) {
converterType = 3;
}
require(
getLiquidityPoolByConfig(converterType, reserveTokens, reserveWeights) == IConverterAnchor(0),
"ERR_ALREADY_EXISTS"
);
IConverterFactory factory = IConverterFactory(addressOf(CONVERTER_FACTORY));
IConverterAnchor anchor = IConverterAnchor(factory.createAnchor(converterType, name, symbol, decimals));
IConverter converter = IConverter(factory.createConverter(converterType, anchor, registry, maxConversionFee));
anchor.acceptOwnership();
converter.acceptOwnership();
for (uint256 i = 0; i < length; i++) {
converter.addReserve(reserveTokens[i], reserveWeights[i]);
}
anchor.transferOwnership(address(converter));
converter.acceptAnchorOwnership();
converter.transferOwnership(msg.sender);
addConverterInternal(converter);
return converter;
}
/**
* @dev adds an existing converter to the registry
* can only be called by the owner
*
* @param converter converter
*/
function addConverter(IConverter converter) public ownerOnly {
require(isConverterValid(converter), "ERR_INVALID_CONVERTER");
addConverterInternal(converter);
}
/**
* @dev removes a converter from the registry
* anyone can remove an existing converter from the registry, as long as the converter is invalid
* note that the owner can also remove valid converters
*
* @param converter converter
*/
function removeConverter(IConverter converter) public {
require(msg.sender == owner || !isConverterValid(converter), "ERR_ACCESS_DENIED");
removeConverterInternal(converter);
}
/**
* @dev returns the number of converter anchors in the registry
*
* @return number of anchors
*/
function getAnchorCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokenCount();
}
/**
* @dev returns the list of converter anchors in the registry
*
* @return list of anchors
*/
function getAnchors() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokens();
}
/**
* @dev returns the converter anchor at a given index
*
* @param index index
*
* @return anchor at the given index
*/
function getAnchor(uint256 index) public view override returns (IConverterAnchor) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartToken(index);
}
/**
* @dev checks whether or not a given value is a converter anchor
*
* @param value value
*
* @return true if the given value is an anchor, false if not
*/
function isAnchor(address value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isSmartToken(value);
}
/**
* @dev returns the number of liquidity pools in the registry
*
* @return number of liquidity pools
*/
function getLiquidityPoolCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPoolCount();
}
/**
* @dev returns the list of liquidity pools in the registry
*
* @return list of liquidity pools
*/
function getLiquidityPools() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPools();
}
/**
* @dev returns the liquidity pool at a given index
*
* @param index index
*
* @return liquidity pool at the given index
*/
function getLiquidityPool(uint256 index) public view override returns (IConverterAnchor) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPool(index);
}
/**
* @dev checks whether or not a given value is a liquidity pool
*
* @param value value
*
* @return true if the given value is a liquidity pool, false if not
*/
function isLiquidityPool(address value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isLiquidityPool(value);
}
/**
* @dev returns the number of convertible tokens in the registry
*
* @return number of convertible tokens
*/
function getConvertibleTokenCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenCount();
}
/**
* @dev returns the list of convertible tokens in the registry
*
* @return list of convertible tokens
*/
function getConvertibleTokens() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokens();
}
/**
* @dev returns the convertible token at a given index
*
* @param index index
*
* @return convertible token at the given index
*/
function getConvertibleToken(uint256 index) public view override returns (IReserveToken) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleToken(index);
}
/**
* @dev checks whether or not a given value is a convertible token
*
* @param value value
*
* @return true if the given value is a convertible token, false if not
*/
function isConvertibleToken(address value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleToken(value);
}
/**
* @dev returns the number of converter anchors associated with a given convertible token
*
* @param convertibleToken convertible token
*
* @return number of anchors associated with the given convertible token
*/
function getConvertibleTokenAnchorCount(IReserveToken convertibleToken) public view override returns (uint256) {
return
IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount(
convertibleToken
);
}
/**
* @dev returns the list of converter anchors associated with a given convertible token
*
* @param convertibleToken convertible token
*
* @return list of anchors associated with the given convertible token
*/
function getConvertibleTokenAnchors(IReserveToken convertibleToken)
public
view
override
returns (address[] memory)
{
return
IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokens(convertibleToken);
}
/**
* @dev returns the converter anchor associated with a given convertible token at a given index
*
* @param index index
*
* @return anchor associated with the given convertible token at the given index
*/
function getConvertibleTokenAnchor(IReserveToken convertibleToken, uint256 index)
public
view
override
returns (IConverterAnchor)
{
return
IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartToken(
convertibleToken,
index
);
}
/**
* @dev checks whether or not a given value is a converter anchor of a given convertible token
*
* @param convertibleToken convertible token
* @param value value
*
* @return true if the given value is an anchor of the given convertible token, false if not
*/
function isConvertibleTokenAnchor(IReserveToken convertibleToken, address value)
public
view
override
returns (bool)
{
return
IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleTokenSmartToken(
convertibleToken,
value
);
}
/**
* @dev returns a list of converters for a given list of anchors
* this is a utility function that can be used to reduce the number of calls to the contract
*
* @param anchors list of converter anchors
*
* @return list of converters
*/
function getConvertersByAnchors(address[] memory anchors) public view returns (IConverter[] memory) {
IConverter[] memory converters = new IConverter[](anchors.length);
for (uint256 i = 0; i < anchors.length; i++) {
converters[i] = IConverter(payable(IConverterAnchor(anchors[i]).owner()));
}
return converters;
}
/**
* @dev checks whether or not a given converter is valid
*
* @param converter converter
*
* @return true if the given converter is valid, false if not
*/
function isConverterValid(IConverter converter) public view returns (bool) {
// verify that the converter is active
return converter.token().owner() == address(converter);
}
/**
* @dev checks if a liquidity pool with given configuration is already registered
*
* @param converter converter with specific configuration
*
* @return if a liquidity pool with the same configuration is already registered
*/
function isSimilarLiquidityPoolRegistered(IConverter converter) public view returns (bool) {
uint256 reserveTokenCount = converter.connectorTokenCount();
IReserveToken[] memory reserveTokens = new IReserveToken[](reserveTokenCount);
uint32[] memory reserveWeights = new uint32[](reserveTokenCount);
// get the reserve-configuration of the converter
for (uint256 i = 0; i < reserveTokenCount; i++) {
IReserveToken reserveToken = converter.connectorTokens(i);
reserveTokens[i] = reserveToken;
reserveWeights[i] = getReserveWeight(converter, reserveToken);
}
// return if a liquidity pool with the same configuration is already registered
return
getLiquidityPoolByConfig(getConverterType(converter, reserveTokenCount), reserveTokens, reserveWeights) !=
IConverterAnchor(0);
}
/**
* @dev searches for a liquidity pool with specific configuration
*
* @param converterType converter type
* @param reserveTokens reserve tokens
* @param reserveWeights reserve weights
*
* @return the liquidity pool, or zero if no such liquidity pool exists
*/
function getLiquidityPoolByConfig(
uint16 converterType,
IReserveToken[] memory reserveTokens,
uint32[] memory reserveWeights
) public view override returns (IConverterAnchor) {
// verify that the input parameters represent a valid liquidity pool
if (reserveTokens.length == reserveWeights.length && reserveTokens.length > 1) {
// get the anchors of the least frequent token (optimization)
address[] memory convertibleTokenAnchors = getLeastFrequentTokenAnchors(reserveTokens);
// search for a converter with the same configuration
for (uint256 i = 0; i < convertibleTokenAnchors.length; i++) {
IConverterAnchor anchor = IConverterAnchor(convertibleTokenAnchors[i]);
IConverter converter = IConverter(payable(anchor.owner()));
if (isConverterReserveConfigEqual(converter, converterType, reserveTokens, reserveWeights)) {
return anchor;
}
}
}
return IConverterAnchor(0);
}
/**
* @dev adds a converter anchor to the registry
*
* @param anchor converter anchor
*/
function addAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal {
converterRegistryData.addSmartToken(anchor);
emit ConverterAnchorAdded(anchor);
emit SmartTokenAdded(anchor);
}
/**
* @dev removes a converter anchor from the registry
*
* @param anchor converter anchor
*/
function removeAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal {
converterRegistryData.removeSmartToken(anchor);
emit ConverterAnchorRemoved(anchor);
emit SmartTokenRemoved(anchor);
}
/**
* @dev adds a liquidity pool to the registry
*
* @param liquidityPoolAnchor liquidity pool converter anchor
*/
function addLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor)
internal
{
converterRegistryData.addLiquidityPool(liquidityPoolAnchor);
emit LiquidityPoolAdded(liquidityPoolAnchor);
}
/**
* @dev removes a liquidity pool from the registry
*
* @param liquidityPoolAnchor liquidity pool converter anchor
*/
function removeLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor)
internal
{
converterRegistryData.removeLiquidityPool(liquidityPoolAnchor);
emit LiquidityPoolRemoved(liquidityPoolAnchor);
}
/**
* @dev adds a convertible token to the registry
*
* @param convertibleToken convertible token
* @param anchor associated converter anchor
*/
function addConvertibleToken(
IConverterRegistryData converterRegistryData,
IReserveToken convertibleToken,
IConverterAnchor anchor
) internal {
converterRegistryData.addConvertibleToken(convertibleToken, anchor);
emit ConvertibleTokenAdded(convertibleToken, anchor);
}
/**
* @dev removes a convertible token from the registry
*
* @param convertibleToken convertible token
* @param anchor associated converter anchor
*/
function removeConvertibleToken(
IConverterRegistryData converterRegistryData,
IReserveToken convertibleToken,
IConverterAnchor anchor
) internal {
converterRegistryData.removeConvertibleToken(convertibleToken, anchor);
emit ConvertibleTokenRemoved(convertibleToken, anchor);
}
/**
* @dev checks whether or not a given configuration depicts a standard pool
*
* @param reserveWeights reserve weights
*
* @return true if the given configuration depicts a standard pool, false otherwise
*/
function isStandardPool(uint32[] memory reserveWeights) internal pure virtual returns (bool) {
return
reserveWeights.length == 2 &&
reserveWeights[0] == PPM_RESOLUTION / 2 &&
reserveWeights[1] == PPM_RESOLUTION / 2;
}
function addConverterInternal(IConverter converter) private {
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
IConverterAnchor anchor = IConverter(converter).token();
uint256 reserveTokenCount = converter.connectorTokenCount();
// add the converter anchor
addAnchor(converterRegistryData, anchor);
if (reserveTokenCount > 1) {
addLiquidityPool(converterRegistryData, anchor);
} else {
addConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor);
}
// add all reserve tokens
for (uint256 i = 0; i < reserveTokenCount; i++) {
addConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor);
}
}
function removeConverterInternal(IConverter converter) private {
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
IConverterAnchor anchor = IConverter(converter).token();
uint256 reserveTokenCount = converter.connectorTokenCount();
// remove the converter anchor
removeAnchor(converterRegistryData, anchor);
if (reserveTokenCount > 1) {
removeLiquidityPool(converterRegistryData, anchor);
} else {
removeConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor);
}
// remove all reserve tokens
for (uint256 i = 0; i < reserveTokenCount; i++) {
removeConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor);
}
}
function getLeastFrequentTokenAnchors(IReserveToken[] memory reserveTokens)
private
view
returns (address[] memory)
{
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
uint256 minAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount(reserveTokens[0]);
uint256 index = 0;
// find the reserve token which has the smallest number of converter anchors
for (uint256 i = 1; i < reserveTokens.length; i++) {
uint256 convertibleTokenAnchorCount =
converterRegistryData.getConvertibleTokenSmartTokenCount(reserveTokens[i]);
if (minAnchorCount > convertibleTokenAnchorCount) {
minAnchorCount = convertibleTokenAnchorCount;
index = i;
}
}
return converterRegistryData.getConvertibleTokenSmartTokens(reserveTokens[index]);
}
function isConverterReserveConfigEqual(
IConverter converter,
uint16 converterType,
IReserveToken[] memory reserveTokens,
uint32[] memory reserveWeights
) private view returns (bool) {
uint256 reserveTokenCount = converter.connectorTokenCount();
if (converterType != getConverterType(converter, reserveTokenCount)) {
return false;
}
if (reserveTokens.length != reserveTokenCount) {
return false;
}
for (uint256 i = 0; i < reserveTokens.length; i++) {
if (reserveWeights[i] != getReserveWeight(converter, reserveTokens[i])) {
return false;
}
}
return true;
}
// utility to get the reserve weight (including from older converters that don't support the new getReserveWeight function)
function getReserveWeight(IConverter converter, IReserveToken reserveToken) private view returns (uint32) {
(, uint32 weight, , , ) = converter.connectors(reserveToken);
return weight;
}
bytes4 private constant CONVERTER_TYPE_FUNC_SELECTOR = bytes4(keccak256("converterType()"));
// utility to get the converter type (including from older converters that don't support the new converterType function)
function getConverterType(IConverter converter, uint256 reserveTokenCount) private view returns (uint16) {
(bool success, bytes memory returnData) =
address(converter).staticcall(abi.encodeWithSelector(CONVERTER_TYPE_FUNC_SELECTOR));
if (success && returnData.length == 32) {
return abi.decode(returnData, (uint16));
}
return reserveTokenCount > 1 ? 1 : 0;
}
/**
* @dev deprecated, backward compatibility, use `getAnchorCount`
*/
function getSmartTokenCount() public view returns (uint256) {
return getAnchorCount();
}
/**
* @dev deprecated, backward compatibility, use `getAnchors`
*/
function getSmartTokens() public view returns (address[] memory) {
return getAnchors();
}
/**
* @dev deprecated, backward compatibility, use `getAnchor`
*/
function getSmartToken(uint256 index) public view returns (IConverterAnchor) {
return getAnchor(index);
}
/**
* @dev deprecated, backward compatibility, use `isAnchor`
*/
function isSmartToken(address value) public view returns (bool) {
return isAnchor(value);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchorCount`
*/
function getConvertibleTokenSmartTokenCount(IReserveToken convertibleToken) public view returns (uint256) {
return getConvertibleTokenAnchorCount(convertibleToken);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchors`
*/
function getConvertibleTokenSmartTokens(IReserveToken convertibleToken) public view returns (address[] memory) {
return getConvertibleTokenAnchors(convertibleToken);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchor`
*/
function getConvertibleTokenSmartToken(IReserveToken convertibleToken, uint256 index)
public
view
returns (IConverterAnchor)
{
return getConvertibleTokenAnchor(convertibleToken, index);
}
/**
* @dev deprecated, backward compatibility, use `isConvertibleTokenAnchor`
*/
function isConvertibleTokenSmartToken(IReserveToken convertibleToken, address value) public view returns (bool) {
return isConvertibleTokenAnchor(convertibleToken, value);
}
/**
* @dev deprecated, backward compatibility, use `getConvertersByAnchors`
*/
function getConvertersBySmartTokens(address[] memory smartTokens) public view returns (IConverter[] memory) {
return getConvertersByAnchors(smartTokens);
}
/**
* @dev deprecated, backward compatibility, use `getLiquidityPoolByConfig`
*/
function getLiquidityPoolByReserveConfig(IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights)
public
view
returns (IConverterAnchor)
{
return getLiquidityPoolByConfig(reserveTokens.length > 1 ? 1 : 0, reserveTokens, reserveWeights);
}
}
|
adds a liquidity pool to the registry liquidityPoolAnchor liquidity pool converter anchor/
|
function addLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor)
internal
{
converterRegistryData.addLiquidityPool(liquidityPoolAnchor);
emit LiquidityPoolAdded(liquidityPoolAnchor);
}
| 15,797,615
|
pragma solidity ^0.8.0;
import "./DeliveryContract.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract OrderLogicContract{
// Authorities
address public authority;
// key:value store
uint public orderCount = 0;
mapping(uint => Order) public orders;
mapping(uint => ConfirmationMechanism) public storeShipnent;
mapping(uint => ConfirmationMechanism) public customerRecievement;
mapping(uint => ConfirmationMechanism) public customerShipment;
mapping(uint => ConfirmationMechanism) public storeRecievement;
mapping(uint => Settlement) public settlements;
mapping(address => uint) public adressOrder;
// STRUCTS
struct Order {
// identificator of the order
uint id;
// roles
address payable customer;
address payable store;
address deliverer;
//
uint costInTotal;
int256 acceptedDate;
//
uint productListHash;
uint returnedProductListHash;
uint returnedListHash;
uint customerInformationHash;
// State
OrderState state;
}
enum OrderState{
CREATED, // 0
PAID, // 1
ACCEPTED, // 2
SHIPPED, // 3
CANCELLED, // 4
DELIVERED, // 5
COMPLETED, // 6
SENTBACK, // 7
RETURNED, // 8
PROPOSALFORSETTLEMENT, // 9
FROZEN, // 10
REFUNDED // 11
}
struct ConfirmationMechanism{
address condignor;
address recipient;
uint256 consignorConfimraiton; // timestamp
uint256 recipientConfimraiton; // timestamp
bool exists; // workaround
}
struct Settlement{
uint refundedAmount;
string reason;
bool accepted;
uint decicedRefundAmount;
bool exists; // workaround
}
constructor() public {
authority = msg.sender;
}
// EVENTS
event OrderStateChanged(
uint orderId,
OrderState state
);
// FUNCTIONS
function createOrder(
address payable _customer,
address payable _store,
address _deliverer,
string memory _productsList,
uint _productCount,
uint _costInTotal
) public returns (uint orderId) {
// add Order
orderCount++;
//ConfirmationMechanism storage empty = ConfirmationMechanism(address(0), address(0), 0,0);
orders[orderCount] = Order( orderCount,
_customer,
_store,
_deliverer,
_costInTotal,
0, 0, 0, 0 , 0,
OrderState.CREATED);
emit OrderStateChanged( orderCount, OrderState.CREATED );
}
function payOrder( uint _orderId) public payable {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the post
Order memory _order = orders[_orderId];
require(_order.state == OrderState.CREATED);
require( _order.costInTotal == msg.value ); // if is enought to pay
// update state
_order.state = OrderState.PAID;
// update order
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function acceptOrder(uint _orderId) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the post
Order memory _order = orders[_orderId];
// Check sender role in order
require(_order.store == msg.sender);
// Check state of the order
require(_order.state == OrderState.PAID);
// update state
_order.state = OrderState.ACCEPTED;
// update order
orders[_orderId] = _order;
// emit event
emit OrderStateChanged( _orderId, _order.state );
}
function returnProducts( uint _orderId,
string memory _productsList ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
require(_order.state == OrderState.DELIVERED);
_order.returnedListHash = 1;
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function makeProposal( uint _orderId, uint _amount, string memory _reason ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
require(_order.state == OrderState.RETURNED );
require(_order.costInTotal >= _amount );
require( msg.sender == _order.store );
settlements[ _orderId ] = Settlement( _amount, _reason, false, 0, true );
_order.state = OrderState.PROPOSALFORSETTLEMENT;
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function makeRefund( uint _orderId ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
require(_order.state == OrderState.RETURNED );
require( msg.sender == _order.store );
// Return payment to cutomer account
//address payable adr= address(_order.customer);
_order.customer.transfer( _order.costInTotal );
_order.state = OrderState.REFUNDED;
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function payBasedProposal( Order memory _order, Settlement memory _settlement ) private {
if ( ( _order.state == OrderState.PROPOSALFORSETTLEMENT ) &&
_settlement.accepted){
_order.customer.transfer( _settlement.refundedAmount );
_order.store.transfer(_order.costInTotal - _settlement.refundedAmount );
}else if( ( _order.state == OrderState.FROZEN ) ) {
_order.customer.transfer( _settlement.decicedRefundAmount );
_order.store.transfer( _order.costInTotal - _settlement.decicedRefundAmount );
}
}
function proposalAcceptence( uint _orderId, bool _accept ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
require(_order.state == OrderState.PROPOSALFORSETTLEMENT );
require( msg.sender == _order.customer );
if ( _accept ){
Settlement memory _settlement = settlements[_orderId];
_settlement.accepted = true;
settlements[_orderId] = _settlement;
payBasedProposal( _order, _settlement );
_order.state = OrderState.REFUNDED;
}else{
_order.state = OrderState.FROZEN;
}
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function unfroze( uint _orderId, uint _amount ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
require(_order.state == OrderState.FROZEN );
require( msg.sender == authority ); // block arbitration
require(_order.costInTotal >= _amount );
Settlement memory _settlement = settlements[_orderId];
_settlement.decicedRefundAmount = _amount;
settlements[_orderId] = _settlement;
payBasedProposal( _order , _settlement );
_order.state = OrderState.REFUNDED;
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function cancelOrder( uint _orderId ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the post
Order memory _order = orders[_orderId];
// Role check
require(_order.store == msg.sender ||
_order.customer == msg.sender );
// Order state check
require(_order.state == OrderState.CREATED ||
_order.state == OrderState.PAID ||
_order.state == OrderState.ACCEPTED ||
_order.state == OrderState.SHIPPED);
if ( _order.state != OrderState.CREATED ){ // is payed
// send back payment
_order.customer.transfer( _order.costInTotal );
}
// update state
_order.state = OrderState.CANCELLED;
// update order
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function confirmationMechanism(uint _orderId, address _deliveryContractAdress ) public {
// Check if provided address is smart contract
require( Address.isContract(_deliveryContractAdress) );
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
// Creating communication instance from adress
DeliveryContract del = DeliveryContract(_deliveryContractAdress);
if ( _order.state == OrderState.ACCEPTED ){
// Required function of delivery contract for confirmation of
// delivery act
if ( del.isConfirmed(_orderId, _order.store, _order.deliverer ) ){
_order.state = OrderState.SHIPPED;
}
}else if ( _order.state == OrderState.SHIPPED ){
if ( del.isConfirmed( _orderId, _order.deliverer, _order.customer ) ){
_order.state = OrderState.DELIVERED;
}
}else if ( _order.state == OrderState.DELIVERED ){
if ( del.isConfirmed( _orderId, _order.customer, _order.deliverer ) ){
_order.state = OrderState.SENTBACK;
}
}else if ( _order.state == OrderState.SENTBACK ){
if ( del.isConfirmed( _orderId, _order.deliverer, _order.store ) ){
_order.state = OrderState.RETURNED;
}
}
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
function step( uint _orderId ) public {
// Make sure the id is valid
require(_orderId > 0 && _orderId <= orderCount);
// Fetch the order
Order memory _order = orders[_orderId];
if ( _order.state == OrderState.DELIVERED ){
// Check date of accepted
_order.store.transfer( _order.costInTotal );
_order.state = OrderState.COMPLETED;
orders[_orderId] = _order;
emit OrderStateChanged( _orderId, _order.state );
}
}
}
|
FUNCTIONS add OrderConfirmationMechanism storage empty = ConfirmationMechanism(address(0), address(0), 0,0);
|
function createOrder(
address payable _customer,
address payable _store,
address _deliverer,
string memory _productsList,
uint _productCount,
uint _costInTotal
) public returns (uint orderId) {
orderCount++;
orders[orderCount] = Order( orderCount,
_customer,
_store,
_deliverer,
_costInTotal,
0, 0, 0, 0 , 0,
OrderState.CREATED);
emit OrderStateChanged( orderCount, OrderState.CREATED );
}
| 12,658,991
|
// Copyright (c) William Morriss, 2018
pragma solidity^0.4.19;
import "./lottery.sol";
import "./AppToken.sol";
import "ds-test/test.sol";
contract LotteryMock is Lottery {
function LotteryMock(AppToken _token, Forum _forum) Lottery(_token, _forum) public {}
function setRewardPool(uint256 _rewardPool) public {
rewardPool = _rewardPool;
}
uint256 _now;
function warp(uint256 _warp) external {
_now += _warp;
}
function era() internal view returns (uint256) {
return _now;
}
}
contract RedeemerMock is Redeemer {
AppToken public from;
AppToken public to;
// the current version of solc does not recognize public vars as implementing public view methods
function to() external view returns (AppToken) {
return to;
}
function from() external view returns (AppToken) {
return from;
}
function RedeemerMock(AppToken _from, AppToken _to) public {
from = _from;
to = _to;
}
function redeem() external {
uint256 wad = from.balanceOf(msg.sender);
from.transferFrom(msg.sender, this, wad);
to.transfer(msg.sender, wad);
}
function undo() external {
uint256 wad = to.balanceOf(msg.sender);
to.transferFrom(msg.sender, this, wad);
from.transfer(msg.sender, wad);
}
}
contract Voter {
Lottery lottery;
Forum forum;
AppToken token;
function Voter (Lottery _lottery, Forum _forum, AppToken _token) public {
lottery = _lottery;
forum = _forum;
token = _token;
}
function upvote(uint _index) external {
lottery.upvote(_index);
}
function downvote(uint _index) external {
lottery.downvote(_index);
}
function unvote(uint256 _index) external {
lottery.unvote(_index);
}
function post() external {
forum.post(0x0, 0x0);
}
function postAndUpvote() external {
forum.postAndUpvote(0x0, 0x0);
}
function claim(uint8 _index) external {
lottery.claim(_index);
}
function setToken(AppToken _to) external {
token = _to;
}
function setForum(Forum _forum) external {
forum = _forum;
}
function install(AppToken _token, address _app) external {
_token.install(_app);
}
function redeem(Redeemer _redeemer) external {
ERC20 from = _redeemer.from();
ERC20 to = _redeemer.to();
from.approve(_redeemer, from.balanceOf(this));
_redeemer.redeem();
to.approve(forum, to.balanceOf(this));
to.approve(lottery, to.balanceOf(this));
}
function undo(Redeemer _redeemer) external {
ERC20 from = _redeemer.from();
ERC20 to = _redeemer.to();
to.approve(_redeemer, to.balanceOf(this));
_redeemer.undo();
from.approve(forum, from.balanceOf(this));
from.approve(lottery, from.balanceOf(this));
}
function tryRedeemForumToken(Redeemer _redeemer) external {
lottery.redeem(_redeemer);
}
function tryRedeemLotteryToken(Redeemer _redeemer) external {
lottery.redeem(_redeemer);
}
function tryUndoForumToken(Redeemer _redeemer) external {
lottery.undo(_redeemer);
}
function tryUndoLotteryToken(Redeemer _redeemer) external {
lottery.undo(_redeemer);
}
function trySetForumOwner(address _owner) external {
forum.setOwner(_owner);
}
function trySetLotteryOwner(address _owner) external {
lottery.setOwner(_owner);
}
}
contract AppTokenMock is AppToken {
function AppTokenMock(uint256 balance, address admin1, address admin2, address admin3) AppToken(admin1, admin2, admin3) public {
balances[msg.sender] = balance;
Transfer(0x0, msg.sender, balance);
}
}
contract LotteryTest is DSTest, ForumEvents {
Voter admin1;
Voter admin2;
AppToken token;
Forum forum;
LotteryMock lottery;
AppToken successorToken;
Redeemer redeemer;
function setUp() public {
admin1 = new Voter(Lottery(0x0), Forum(0x0), AppToken(0x0));
admin2 = new Voter(Lottery(0x0), Forum(0x0), AppToken(0x0));
uint256 supply = 1000000000 ether;
token = new AppTokenMock(supply, msg.sender, admin1, admin2);
admin1.setToken(token);
admin2.setToken(token);
forum = new Forum();
admin1.setForum(forum);
admin2.setForum(forum);
lottery = new LotteryMock(token, forum);
forum.setBeneficiary(lottery);
successorToken = new AppTokenMock(supply, msg.sender, admin1, admin2);
redeemer = new RedeemerMock(token, successorToken);
successorToken.transfer(redeemer, supply);
}
modifier test {
admin1.install(token, lottery);
admin2.install(token, lottery);
admin1.install(successorToken, lottery);
admin2.install(successorToken, lottery);
require(token.installed(lottery));
_;
}
function testFail_noInstallPost() public {
forum.post(0x0,0x0);
}
function testFail_noInstallVote() public {
lottery.upvote(0);
}
function test_reward() public test {
lottery.setRewardPool(5000);
assertEq(lottery.reward(0), 2000);
assertEq(lottery.reward(1), 1250);
assertEq(lottery.reward(2), 1000);
assertEq(lottery.reward(3), 500);
assertEq(lottery.reward(4), 250);
assertEq(lottery.rewardPool(),
lottery.reward(0)
+ lottery.reward(1)
+ lottery.reward(2)
+ lottery.reward(3)
+ lottery.reward(4)
);
}
function testFail_earlyEpoch() public test {
lottery.endEpoch();
}
function testFail_earlySecondEpoch() public test {
nextEpoch();
lottery.endEpoch();
}
function assertNoWinners() internal {
assertEq(lottery.payouts(0), 0);
assertEq(lottery.payouts(1), 0);
assertEq(lottery.payouts(2), 0);
assertEq(lottery.payouts(3), 0);
assertEq(lottery.payouts(4), 0);
}
function nextEpoch() internal {
lottery.warp(1 days);
lottery.endEpoch();
}
function test_emptyEpoch() public test {
nextEpoch();
assertNoWinners();
nextEpoch();
assertNoWinners();
forum.post(0x0, 0x0);
lottery.upvote(1);
nextEpoch();
assertNoWinners();
}
function test_epoch() public test {
forum.post(0x0, 0x0);
forum.post(0x0, 0x0);
nextEpoch();
assertNoWinners();
assertEq(lottery.epochPrior(), 0);
assertEq(lottery.epochCurrent(), 3);
forum.post(0x0, 0x0);
lottery.upvote(2);
lottery.upvote(1);
lottery.upvote(3);
nextEpoch();
assertEq(lottery.payouts(0), this);
assertEq(lottery.payouts(1), this);
assertEq(lottery.payouts(2), 0);
assertEq(lottery.payouts(3), 0);
assertEq(lottery.payouts(4), 0);
assertEq(lottery.epochCurrent(), lottery.epochPrior() + 1);
uint256 balance = token.balanceOf(this);
lottery.claim(0);
lottery.claim(1);
uint256 balanceAfter = token.balanceOf(this);
assertEq(balance + lottery.reward(0) + lottery.reward(1), balanceAfter);
lottery.downvote(3);
nextEpoch();
assertNoWinners();
}
function test_epochRanking() public test {
// 1
forum.post(0x0, 0x0);
// 2
forum.post(0x0, 0x0);
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
// 3
v1.post();
Voter v2 = new Voter(lottery, forum, token);
token.transfer(v2, 10 ether);
// 4
v2.post();
nextEpoch();
assertNoWinners();
// 1: +1
lottery.upvote(1);
v1.upvote(1);
v2.downvote(1);
// 2: -1
lottery.downvote(2);
v1.upvote(2);
v2.downvote(2);
// 3: +3
lottery.upvote(3);
v1.upvote(3);
v2.upvote(3);
// 4: +2
lottery.upvote(4);
v2.upvote(4);
nextEpoch();
assertEq(lottery.payouts(0), v1);
assertEq(lottery.payouts(1), v2);
assertEq(lottery.payouts(2), this);
assertEq(lottery.payouts(3), 0x0);
v1.claim(0);
v2.claim(1);
lottery.claim(2);
}
function test_upvoteDownvote() public test {
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
Voter v2 = new Voter(lottery, forum, token);
token.transfer(v2, 10 ether);
lottery.upvote(1);
assertEq(lottery.votes(1), 1);
v1.upvote(1);
assertEq(lottery.votes(1), 2);
v1.postAndUpvote();
v2.upvote(1);
assertEq(lottery.votes(1), 3);
lottery.downvote(1);
assertEq(lottery.votes(1), 1);
v1.downvote(1);
assertEq(lottery.votes(1), -1);
v2.downvote(1);
assertEq(lottery.votes(1), -3);
v2.downvote(2);
assertEq(lottery.votes(2), -1);
v2.downvote(2);
assertEq(lottery.votes(2), -1);
v1.downvote(2);
assertEq(lottery.votes(2), -2);
lottery.downvote(2);
assertEq(lottery.votes(2), -3);
v1.postAndUpvote();
assertEq(lottery.votes(2), -1);
assertEq(lottery.votes(3), 0);
v2.unvote(3);
assertEq(lottery.votes(3), 0);
v1.upvote(3);
assertEq(lottery.votes(3), 1);
v2.upvote(3);
assertEq(lottery.votes(3), 2);
v2.downvote(3);
assertEq(lottery.votes(3), 0);
v2.postAndUpvote();
assertEq(lottery.votes(3), 2);
v2.unvote(3);
assertEq(lottery.votes(3), 1);
}
function testFail_noTokens() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.upvote(1);
}
function redeem() internal {
lottery.redeem(redeemer);
uint256 balanceBefore = token.balanceOf(this);
token.approve(redeemer, balanceBefore);
redeemer.redeem();
assertEq(balanceBefore, successorToken.balanceOf(this));
}
function undo() internal {
lottery.undo(redeemer);
uint256 balanceBefore = successorToken.balanceOf(this);
successorToken.approve(redeemer, balanceBefore);
redeemer.undo();
assertEq(token.balanceOf(this), balanceBefore);
}
function test_ownerUpgrade() public test {
assertEq(forum.owner(), this);
forum.post(0x0, 0x0);
forum.postAndUpvote(0x0, 0x0);
redeem();
forum.post(0x0, 0x0);
forum.postAndUpvote(0x0, 0x0);
undo();
forum.post(0x0, 0x0);
forum.postAndUpvote(0x0, 0x0);
}
function testFail_forumUpgrade() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.tryRedeemForumToken(redeemer);
}
function testFail_lotteryUpgrade() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.tryRedeemLotteryToken(redeemer);
}
function testFail_forumDowngrade() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.tryUndoForumToken(redeemer);
}
function testFail_lotteryDowngrade() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.tryUndoLotteryToken(redeemer);
}
function testFail_lotterySetOwner() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.trySetLotteryOwner(v1);
}
function testFail_forumSetOwner() public test {
Voter v1 = new Voter(lottery, forum, token);
v1.trySetForumOwner(v1);
}
function test_setOwner() public test {
assertEq(forum.owner(), this);
assertEq(lottery.owner(), this);
Voter v1 = new Voter(lottery, forum, token);
forum.setOwner(v1);
lottery.setOwner(v1);
v1.trySetForumOwner(this);
v1.trySetLotteryOwner(this);
forum.setOwner(v1);
lottery.setOwner(v1);
v1.trySetForumOwner(this);
v1.trySetLotteryOwner(this);
}
function test_postEvents() public test {
expectEventsExact(forum);
Topic(0x0, 0x0);
Topic(0x0, keccak256("Hello"));
Topic(0x2, keccak256("World"));
forum.post(0x0, 0x0);
forum.post(0x0, keccak256("Hello"));
forum.postAndUpvote(0x2, keccak256("World"));
}
function test_redeemerReward() public test {
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
// 1
v1.post();
// 2
forum.post(0x0, 0x0);
v1.upvote(1);
lottery.upvote(1);
nextEpoch();
redeem();
assertNoWinners();
v1.redeem(redeemer);
v1.upvote(2);
nextEpoch();
assertEq(lottery.payouts(0), v1);
assertEq(lottery.payouts(1), this);
assertEq(lottery.payouts(2), 0x0);
v1.claim(0);
undo();
lottery.claim(1);
nextEpoch();
assertNoWinners();
}
function test_sixPosts() public test {
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
Voter v2 = new Voter(lottery, forum, token);
token.transfer(v2, 10 ether);
Voter v3 = new Voter(lottery, forum, token);
token.transfer(v3, 10 ether);
// 1 : 4
v1.postAndUpvote();
lottery.upvote(1);
v2.upvote(1);
v3.upvote(1);
// 2 : 3
v2.postAndUpvote();
lottery.upvote(2);
v3.upvote(2);
// 3 : 1
v3.postAndUpvote();
lottery.downvote(3);
v2.upvote(3);
// 4 : 2
forum.postAndUpvote(0x0, 0x0);
v1.upvote(4);
// 5 : 1
forum.post(0x0, 0x0);
lottery.upvote(5);
// 6 : 3
v3.postAndUpvote();
v1.upvote(6);
lottery.upvote(6);
nextEpoch();
assertNoWinners();
nextEpoch();
assertEq(lottery.payouts(0), v1);
assertEq(lottery.payouts(1), v3);
assertEq(lottery.payouts(2), v2);
assertEq(lottery.payouts(3), this);
assertEq(lottery.payouts(4), this);
v1.claim(0);
v3.claim(1);
v2.claim(2);
lottery.claim(3);
lottery.claim(4);
nextEpoch();
assertNoWinners();
assertEq(lottery.rewardPool(), 0);
}
function test_sevenPosts() public test {
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
Voter v2 = new Voter(lottery, forum, token);
token.transfer(v2, 10 ether);
Voter v3 = new Voter(lottery, forum, token);
token.transfer(v3, 10 ether);
// 1 : 2
v1.postAndUpvote();
lottery.downvote(1);
v2.upvote(1);
v3.upvote(1);
// 2 : 3
v2.postAndUpvote();
lottery.upvote(2);
v3.upvote(2);
// 3 : 2
v3.postAndUpvote();
lottery.downvote(3);
v2.upvote(3);
v1.upvote(3);
// 4 : 2
forum.postAndUpvote(0x0, 0x0);
v1.upvote(4);
// 5 : 1
forum.post(0x0, 0x0);
lottery.upvote(5);
// 6 : 0
v2.postAndUpvote();
lottery.downvote(6);
// 7 : 2
v3.postAndUpvote();
v1.upvote(7);
nextEpoch();
assertNoWinners();
nextEpoch();
assertEq(lottery.payouts(0), v2);
assertEq(lottery.payouts(1), v3);
assertEq(lottery.payouts(2), this);
assertEq(lottery.payouts(3), v3);
assertEq(lottery.payouts(4), v1);
v2.claim(0);
v3.claim(1);
lottery.claim(2);
v3.claim(3);
v1.claim(4);
nextEpoch();
assertNoWinners();
assertEq(lottery.rewardPool(), 0);
}
}
|
1 2 3 4 1: +1 2: -1 3: +3 4: +2
|
function test_epochRanking() public test {
forum.post(0x0, 0x0);
forum.post(0x0, 0x0);
Voter v1 = new Voter(lottery, forum, token);
token.transfer(v1, 10 ether);
v1.post();
Voter v2 = new Voter(lottery, forum, token);
token.transfer(v2, 10 ether);
v2.post();
nextEpoch();
assertNoWinners();
lottery.upvote(1);
v1.upvote(1);
v2.downvote(1);
lottery.downvote(2);
v1.upvote(2);
v2.downvote(2);
lottery.upvote(3);
v1.upvote(3);
v2.upvote(3);
lottery.upvote(4);
v2.upvote(4);
nextEpoch();
assertEq(lottery.payouts(0), v1);
assertEq(lottery.payouts(1), v2);
assertEq(lottery.payouts(2), this);
assertEq(lottery.payouts(3), 0x0);
v1.claim(0);
v2.claim(1);
lottery.claim(2);
}
| 6,441,457
|
./partial_match/1/0x412e5a36BDE71AA2c38e1c0E26BAAf7F2f0Bc24a/sources/PusdPool.sol
|
require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); If pausing, set paused price; else if unpausing, clear pausedPrice
|
function toggleCollateralPrice() external onlyByOwnerOrGovernance {
if(collateralPricePaused == false){
pausedPrice = getCollateralPrice();
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
}
| 4,072,879
|
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/CDPVault_TypeA.sol
|
Liquidates multiple unsafe positions by selling as much collateral as required to cover the debt in order to make the positions safe again. The collateral can be bought at a discount (`liquidationDiscount`) to the current spot price. The liquidator has to provide the amount he wants repay or sell (`repayAmounts`) for each position. From that repay amount a penalty (`liquidationPenalty`) is subtracted to mitigate against profitable self liquidations. If the available collateral of a position is not sufficient to cover the debt the vault is able to apply for a bail out from the global Buffer, any residual bad debt not covered by the Buffer will be attributed to the credit delegators. The liquidator has to approve the vault to transfer the sum of `repayAmounts`. owners Owners of the positions to liquidate repayAmounts Amounts the liquidator wants to repay for each position [wad] accrues bad debt in all liquidated positions calculate position debt and collateral value verify that the position is indeed unsafe calculate the max. amount of debt we can recover with the position's collateral in order to move the health factor back to the target health factor account any residual debt as bad debt if the position does not have any collateral left try absorbing any accrued bad debt by applying for a bail out and mark down the residual bad debt apply for a bail out from the Buffer
|
function liquidatePositions(address[] calldata owners, uint256[] memory repayAmounts) external whenNotPaused {
if (owners.length != repayAmounts.length) revert CDPVault__liquidatePositions_argLengthMismatch();
GlobalIRS memory globalIRS = getGlobalIRS();
VaultConfig memory vaultConfig_ = vaultConfig;
LiquidationConfig memory liquidationConfig_ = liquidationConfig;
uint256 spotPrice_ = spotPrice();
ExchangeCache memory cache;
cache.globalIRS = globalIRS;
cache.totalNormalDebt = totalNormalDebt;
cache.debtFloor = vaultConfig.debtFloor;
cache.settlementRate = wmul(spotPrice_, liquidationConfig.liquidationDiscount);
cache.settlementPenalty = liquidationConfig.liquidationPenalty;
uint64 rateAccumulator = _calculateRateAccumulator(globalIRS, cache.totalNormalDebt);
uint256 accruedBadDebt;
for (uint256 i; i < owners.length; ) {
address owner = owners[i];
if (!(owner == address(0) || repayAmounts[i] == 0)) {
Position memory position = positions[owner];
PositionIRS memory positionIRS = _getUpdatedPositionIRS(owner, position.normalDebt, rateAccumulator);
uint256 debt = calculateDebt(position.normalDebt, rateAccumulator, positionIRS.accruedRebate);
if (spotPrice_ == 0 || _isCollateralized(
debt, position.collateral, spotPrice_, vaultConfig_.liquidationRatio
)) revert CDPVault__liquidatePosition_notUnsafe();
uint256 maxDebtToRecover;
{
uint256 nominator;
{
uint256 collateralValue = wdiv(wmul(position.collateral, spotPrice_), vaultConfig_.liquidationRatio);
nominator = wmul(liquidationConfig_.targetHealthFactor, debt) - collateralValue;
}
uint256 discountRatio = wmul(vaultConfig_.liquidationRatio, liquidationConfig_.liquidationDiscount);
uint256 denominator = wmul(liquidationConfig_.targetHealthFactor, cache.settlementPenalty)
- wdiv(WAD, discountRatio);
maxDebtToRecover = wdiv(nominator, denominator);
}
if (position.collateral == 0 && position.normalDebt > 0) {
accruedBadDebt += calculateDebt(
position.normalDebt, positionIRS.snapshotRateAccumulator, positionIRS.accruedRebate
);
delete positions[owner];
}
}
}
cache.globalIRS,
cache.accruedInterest + wmul(cache.creditExchanged, WAD - cache.settlementPenalty),
cache.totalNormalDebt,
spotPrice_,
vaultConfig_.globalLiquidationRatio
);
if (accruedBadDebt != 0) {
buffer.bailOut(accruedBadDebt);
}
}
| 16,850,723
|
./full_match/97/0x0867102793a9015409Fb41B436bB282Ee6e96fC8/sources/project_/contracts/CollectionMethods.sol
|
transfers the ERC 20 tokens from _tokenId(this contract) to _to address
|
function _transferERC20(
uint256 _tokenId,
address _to,
address _erc20Contract,
uint256 _value
) private {
require(_to != address(0), "0 address given");
removeERC20(_tokenId, _erc20Contract, _value);
require(
IERC20(_erc20Contract).transfer(_to, _value),
"transfer failed."
);
emit ERC20Transferred(_tokenId, _to, _erc20Contract, _value);
}
| 3,277,474
|
./partial_match/1313161554/0xDF6FF39459eE846620F11Cc62e33088C55da665a/sources/Storage.sol
|
require(msg.sender == admin, "You can't do that");
|
function setHighestBid(
uint256 tokenId,
uint256 auctionId,
uint256 hb
) public override {
require(msg.sender == parent, "You can't do that");
highestBid[tokenId][auctionId] = hb;
}
| 16,924,651
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.6.8;
/*
* @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/introspection/IERC165.sol@v3.4.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@v3.4.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/IERC721Metadata.sol@v3.4.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/IERC721Enumerable.sol@v3.4.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/token/ERC721/IERC721Receiver.sol@v3.4.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/introspection/ERC165.sol@v3.4.0
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File @openzeppelin/contracts/math/SafeMath.sol@v3.4.0
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/Address.sol@v3.4.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/EnumerableSet.sol@v3.4.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/EnumerableMap.sol@v3.4.0
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File @openzeppelin/contracts/utils/Strings.sol@v3.4.0
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/79dd498b16b957399f84b9aa7e720f98f9eb83e3/contracts/cryptography/ECDSA.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla implementation from an openzeppelin version.
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File @openzeppelin/contracts/token/ERC721/ERC721.sol@v3.4.0
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File @openzeppelin/contracts/token/ERC721/ERC721Burnable.sol@v3.4.0
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// File @openzeppelin/contracts/access/Ownable.sol@v3.4.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 contracts/ChipmunksAndFriends.sol
contract ChipmunksAndFriends is ERC721Burnable, Ownable {
using ECDSA for bytes32;
uint256 constant public PRICE = 0.055 ether;
uint256 constant public TOTAL_SUPPLY = 8888;
uint256 constant public REVEAL_TIMESTAMP = 0;
uint256 constant public MAX_MINT_PER_TX = 20;
uint256 public startingIndex;
uint256 public startingIndexBlock;
struct BoughtCounts {
uint hasMinted;
}
mapping(address => BoughtCounts) public presaleBoughtCounts;
address payable treasury;
address public whitelistSigner = 0x2153ae0f7089508B6E53248f5AE0C8328D6118f9;
bool public privateSaleIsActive = false;
bool public saleIsActive = false;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PRESALE_TYPEHASH = keccak256("Presale(address buyer,uint256 maxCount)");
constructor(address payable _treasury) public ERC721("Chipmunks & Friends", "CHIPMUNK") {
treasury = _treasury;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("ChipmunksAndFriends")),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
function reserveGiveaway(address addr, uint256 amount) public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < amount; i++) {
_safeMint(addr, supply + i);
}
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function flipPrivateSaleState() public onlyOwner {
privateSaleIsActive = !privateSaleIsActive;
}
function mintChipmunks(uint numberOfTokens) public payable {
require(saleIsActive, "ChipmunksAndFriends: Public sale must be active to mint");
require(totalSupply().add(numberOfTokens) <= TOTAL_SUPPLY, "ChipmunksAndFriends: Exceeds max supply");
require(PRICE.mul(numberOfTokens) <= msg.value, "ChipmunksAndFriends: ETH sent is incorrect");
require(numberOfTokens <= MAX_MINT_PER_TX, "ChipmunksAndFriends: Above max tx count");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or
// 2) the first token to be sold after the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == TOTAL_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintChipmunksPrivateSale(uint numberOfTokens, uint256 maxCount, bytes memory signature) public payable {
require(privateSaleIsActive, "ChipmunksAndFriends: Private Sale must be active to mint");
require(totalSupply().add(numberOfTokens) <= TOTAL_SUPPLY, "ChipmunksAndFriends: Exceeds max supply");
require(PRICE.mul(numberOfTokens) <= msg.value, "ChipmunksAndFriends: ETH sent is incorrect");
require(numberOfTokens <= MAX_MINT_PER_TX, "ChipmunksAndFriends: Above max tx count");
// Verify EIP-712 signature
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PRESALE_TYPEHASH, msg.sender, maxCount))));
address recoveredAddress = digest.recover(signature);
require(recoveredAddress != address(0) && recoveredAddress == address(whitelistSigner), "ChipmunksAndFriends: invalid signature");
require(presaleBoughtCounts[msg.sender].hasMinted.add(numberOfTokens) <= maxCount, "ChipmunksAndFriends: Presale max count exceeded");
presaleBoughtCounts[msg.sender].hasMinted = presaleBoughtCounts[msg.sender].hasMinted.add(numberOfTokens);
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or
// 2) the first token to be sold after the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == TOTAL_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public onlyOwner {
require(startingIndex == 0, "ChipmunksAndFriends: Starting index is already set");
require(startingIndexBlock != 0, "ChipmunksAndFriends: Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % TOTAL_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % TOTAL_SUPPLY;
}
}
function setWhitelistSigner(address _whitelistSigner) public onlyOwner {
whitelistSigner = _whitelistSigner;
}
function setTreasuryWallet(address payable _treasury) public onlyOwner {
treasury = _treasury;
}
function claimETH() public {
require(treasury == _msgSender(), "Ownable: caller is not the treasury");
payable(address(treasury)).transfer(address(this).balance);
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (startingIndex == 0) {
return super.tokenURI(0);
}
uint256 moddedId = (tokenId + startingIndex) % TOTAL_SUPPLY;
return super.tokenURI(moddedId);
}
}
|
If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
|
function mintChipmunks(uint numberOfTokens) public payable {
require(saleIsActive, "ChipmunksAndFriends: Public sale must be active to mint");
require(totalSupply().add(numberOfTokens) <= TOTAL_SUPPLY, "ChipmunksAndFriends: Exceeds max supply");
require(PRICE.mul(numberOfTokens) <= msg.value, "ChipmunksAndFriends: ETH sent is incorrect");
require(numberOfTokens <= MAX_MINT_PER_TX, "ChipmunksAndFriends: Above max tx count");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
if (startingIndexBlock == 0 && (totalSupply() == TOTAL_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| 12,157,790
|
./full_match/1/0x6c9829e5aF58E993daC721e3c2de6A1d32e3b37C/sources/contracts/ERC721/ERC721KODACreatorFactory.sol
|
Update the global platforms settings contract
|
function updateSettingsContract(address _newSettings) external {
if (!accessControls.hasAdminRole(msg.sender)) revert OnlyAdmin();
if (_newSettings == address(0)) revert ZeroAddress();
platformSettings = KODASettings(_newSettings);
}
| 9,815,296
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Investors.sol";
import "./Utils.sol";
contract Game is Investors {
event PaidToGame(address to, uint256 amount);
event GameShareChanged(uint256 from, uint256 to);
event InvestorsShareChanged(uint256 from, uint256 to);
event GameShareHolderChanged(address from, address to);
uint public gameShare = 30;
uint public investorsShare = 70;
address public gameShareHolder;
constructor(address _gameShareHolder) {
// set address of game share holder
gameShareHolder = _gameShareHolder;
}
receive() payable external shareShould100 {
uint256 eth_amount = msg.value;
uint256 shareX = Utils.percent(eth_amount, gameShare);
uint256 shareY = Utils.percent(eth_amount, investorsShare);
// transfer amount to game
payable(gameShareHolder).transfer(shareX);
emit PaidToGame(gameShareHolder, shareX);
// transfer remainig amount to all investors
transferAmount(shareY);
}
function percent1(uint numerator, uint denominator, uint precision)
public pure returns(uint quotient) {
// caution, check safe-to-multiply here
uint _numerator = numerator * 10 ** (precision+1);
// with rounding of last digit
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
/**
* @dev change the game share.
* @param _share new share percent of game
*/
function updateGameShare(uint256 _share) onlyOwner public {
require(_share > 0, "Game: game share should be greater then 0");
require(_share <= 100, "Game: Invalid share");
uint256 oldShare = gameShare;
uint256 oldInvestorsShare = investorsShare;
// update game share
gameShare = _share;
// update investors share
investorsShare = (100 - _share);
emit GameShareChanged(oldShare, _share);
emit InvestorsShareChanged(oldInvestorsShare, investorsShare);
}
/**
* @dev change the address of game share holder.
* @param _holder the address of new account
*/
function changeGameShareHolder(address _holder) onlyOwner public {
require(_holder != address(0), "Game: Invalid address for game share holder");
address oldHolder = gameShareHolder;
// change game share holder address
gameShareHolder = _holder;
emit GameShareHolderChanged(oldHolder, _holder);
}
/**
* @dev return share percent of game
*/
function getGameShare() public view returns (uint256) {
return gameShare;
}
/**
* @dev return share percent of all investors
*/
function getInvestorsShare() public view returns (uint256) {
return investorsShare;
}
/**
* @dev Add new investor
* @param account the address of new investor
* @param share the percent of new investor
*/
function addNewInvestor(address account, uint256 share) onlyOwner public {
addInvestor(account, share);
}
function getInvestors() public view returns (address[] memory, uint256[] memory) {
return getAllInvestors();
}
}
|
caution, check safe-to-multiply here with rounding of last digit
|
function percent1(uint numerator, uint denominator, uint precision)
public pure returns(uint quotient) {
uint _numerator = numerator * 10 ** (precision+1);
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
| 5,508,943
|
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "./WeightedStaking.sol";
import "./IStaking.sol";
import "../../rsk/RSKAddrValidator.sol";
import "../Vesting/ITeamVesting.sol";
import "../ApprovalReceiver.sol";
/**
* @title Staking contract.
* @notice Pay-in and pay-out function for staking and withdrawing tokens.
* Staking is delegated and vested: To gain voting power, SOV holders must
* stake their SOV for a given period of time. Aside from Bitocracy
* participation, there's a financially-rewarding reason for staking SOV.
* Tokenholders who stake their SOV receive staking rewards, a pro-rata share
* of the revenue that the platform generates from various transaction fees
* plus revenues from stakers who have a portion of their SOV slashed for
* early unstaking.
* */
contract Staking is IStaking, WeightedStaking, ApprovalReceiver {
/**
* @notice Stake the given amount for the given duration of time.
* @param amount The number of tokens to stake.
* @param until Timestamp indicating the date until which to stake.
* @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself.
* @param delegatee The address of the delegatee or 0x0 if there is none.
* */
function stake(
uint96 amount,
uint256 until,
address stakeFor,
address delegatee
) external {
_stake(msg.sender, amount, until, stakeFor, delegatee, false);
}
/**
* @notice Stake the given amount for the given duration of time.
* @dev This function will be invoked from receiveApproval
* @dev SOV.approveAndCall -> this.receiveApproval -> this.stakeWithApproval
* @param sender The sender of SOV.approveAndCall
* @param amount The number of tokens to stake.
* @param until Timestamp indicating the date until which to stake.
* @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself.
* @param delegatee The address of the delegatee or 0x0 if there is none.
* */
function stakeWithApproval(
address sender,
uint96 amount,
uint256 until,
address stakeFor,
address delegatee
) public onlyThisContract {
_stake(sender, amount, until, stakeFor, delegatee, false);
}
/**
* @notice Send sender's tokens to this contract and update its staked balance.
* @param sender The sender of the tokens.
* @param amount The number of tokens to send.
* @param until The date until which the tokens will be staked.
* @param stakeFor The beneficiary whose stake will be increased.
* @param delegatee The address of the delegatee or stakeFor if default 0x0.
* @param timeAdjusted Whether fixing date to stacking periods or not.
* */
function _stake(
address sender,
uint96 amount,
uint256 until,
address stakeFor,
address delegatee,
bool timeAdjusted
) internal {
require(amount > 0, "Staking::stake: amount of tokens to stake needs to be bigger than 0");
if (!timeAdjusted) {
until = timestampToLockDate(until);
}
require(until > block.timestamp, "Staking::timestampToLockDate: staking period too short");
/// @dev Stake for the sender if not specified otherwise.
if (stakeFor == address(0)) {
stakeFor = sender;
}
/// @dev Delegate for stakeFor if not specified otherwise.
if (delegatee == address(0)) {
delegatee = stakeFor;
}
/// @dev Do not stake longer than the max duration.
if (!timeAdjusted) {
uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION);
if (until > latest) until = latest;
}
uint96 previousBalance = currentBalance(stakeFor, until);
/// @dev Increase stake.
_increaseStake(sender, amount, stakeFor, until);
if (previousBalance == 0) {
/// @dev Regular delegation if it's a first stake.
_delegate(stakeFor, delegatee, until);
} else {
address previousDelegatee = delegates[stakeFor][until];
if (previousDelegatee != delegatee) {
/// @dev Update delegatee.
delegates[stakeFor][until] = delegatee;
/// @dev Decrease stake on previous balance for previous delegatee.
_decreaseDelegateStake(previousDelegatee, until, previousBalance);
/// @dev Add previousBalance to amount.
amount = add96(previousBalance, amount, "Staking::stake: balance overflow");
}
/// @dev Increase stake.
_increaseDelegateStake(delegatee, until, amount);
}
}
/**
* @notice Extend the staking duration until the specified date.
* @param previousLock The old unlocking timestamp.
* @param until The new unlocking timestamp in seconds.
* */
function extendStakingDuration(uint256 previousLock, uint256 until) public {
until = timestampToLockDate(until);
require(previousLock <= until, "Staking::extendStakingDuration: cannot reduce the staking duration");
/// @dev Do not exceed the max duration, no overflow possible.
uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION);
if (until > latest) until = latest;
/// @dev Update checkpoints.
/// @dev TODO James: Can reading stake at block.number -1 cause trouble with multiple tx in a block?
uint96 amount = getPriorUserStakeByDate(msg.sender, previousLock, block.number - 1);
require(amount > 0, "Staking::extendStakingDuration: nothing staked until the previous lock date");
_decreaseUserStake(msg.sender, previousLock, amount);
_increaseUserStake(msg.sender, until, amount);
_decreaseDailyStake(previousLock, amount);
_increaseDailyStake(until, amount);
/// @dev Delegate might change: if there is already a delegate set for the until date, it will remain the delegate for this position
address delegateFrom = delegates[msg.sender][previousLock];
address delegateTo = delegates[msg.sender][until];
if (delegateTo == address(0)) {
delegateTo = delegateFrom;
delegates[msg.sender][until] = delegateFrom;
}
delegates[msg.sender][previousLock] = address(0);
_decreaseDelegateStake(delegateFrom, previousLock, amount);
_increaseDelegateStake(delegateTo, until, amount);
emit ExtendedStakingDuration(msg.sender, previousLock, until);
}
/**
* @notice Send sender's tokens to this contract and update its staked balance.
* @param sender The sender of the tokens.
* @param amount The number of tokens to send.
* @param stakeFor The beneficiary whose stake will be increased.
* @param until The date until which the tokens will be staked.
* */
function _increaseStake(
address sender,
uint96 amount,
address stakeFor,
uint256 until
) internal {
/// @dev Retrieve the SOV tokens.
bool success = SOVToken.transferFrom(sender, address(this), amount);
require(success);
/// @dev Increase staked balance.
uint96 balance = currentBalance(stakeFor, until);
balance = add96(balance, amount, "Staking::increaseStake: balance overflow");
/// @dev Update checkpoints.
_increaseDailyStake(until, amount);
_increaseUserStake(stakeFor, until, amount);
emit TokensStaked(stakeFor, amount, until, balance);
}
/**
* @notice Stake tokens according to the vesting schedule.
* @param amount The amount of tokens to stake.
* @param cliff The time interval to the first withdraw.
* @param duration The staking duration.
* @param intervalLength The length of each staking interval when cliff passed.
* @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself.
* @param delegatee The address of the delegatee or 0x0 if there is none.
* */
function stakesBySchedule(
uint256 amount,
uint256 cliff,
uint256 duration,
uint256 intervalLength,
address stakeFor,
address delegatee
) public {
/**
* @dev Stake them until lock dates according to the vesting schedule.
* Note: because staking is only possible in periods of 2 weeks,
* the total duration might end up a bit shorter than specified
* depending on the date of staking.
* */
uint256 start = timestampToLockDate(block.timestamp + cliff);
if (duration > MAX_DURATION) {
duration = MAX_DURATION;
}
uint256 end = timestampToLockDate(block.timestamp + duration);
uint256 numIntervals = (end - start) / intervalLength + 1;
uint256 stakedPerInterval = amount / numIntervals;
/// @dev stakedPerInterval might lose some dust on rounding. Add it to the first staking date.
if (numIntervals >= 1) {
_stake(msg.sender, uint96(amount - stakedPerInterval * (numIntervals - 1)), start, stakeFor, delegatee, true);
}
/// @dev Stake the rest in 4 week intervals.
for (uint256 i = start + intervalLength; i <= end; i += intervalLength) {
/// @dev Stakes for itself, delegates to the owner.
_stake(msg.sender, uint96(stakedPerInterval), i, stakeFor, delegatee, true);
}
}
/**
* @notice Withdraw the given amount of tokens if they are unlocked.
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* @param receiver The receiver of the tokens. If not specified, send to the msg.sender
* */
function withdraw(
uint96 amount,
uint256 until,
address receiver
) public {
_withdraw(amount, until, receiver, false);
}
/**
* @notice Withdraw the given amount of tokens.
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* @param receiver The receiver of the tokens. If not specified, send to the msg.sender
* @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting
* */
function governanceWithdraw(
uint96 amount,
uint256 until,
address receiver
) public {
require(vestingWhitelist[msg.sender], "unauthorized");
_withdraw(amount, until, receiver, true);
}
/**
* @notice Withdraw tokens for vesting contract.
* @param vesting The address of Vesting contract.
* @param receiver The receiver of the tokens. If not specified, send to the msg.sender
* @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting.
* */
function governanceWithdrawVesting(address vesting, address receiver) public onlyOwner {
vestingWhitelist[vesting] = true;
ITeamVesting(vesting).governanceWithdrawTokens(receiver);
vestingWhitelist[vesting] = false;
emit VestingTokensWithdrawn(vesting, receiver);
}
/**
* @notice Send user' staked tokens to a receiver taking into account punishments.
* Sovryn encourages long-term commitment and thinking. When/if you unstake before
* the end of the staking period, a percentage of the original staking amount will
* be slashed. This amount is also added to the reward pool and is distributed
* between all other stakers.
*
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* @param receiver The receiver of the tokens. If not specified, send to the msg.sender
* @param isGovernance Whether all tokens (true)
* or just unlocked tokens (false).
* */
function _withdraw(
uint96 amount,
uint256 until,
address receiver,
bool isGovernance
) internal {
until = _adjustDateForOrigin(until);
_validateWithdrawParams(amount, until);
/// @dev Determine the receiver.
if (receiver == address(0)) receiver = msg.sender;
/// @dev Update the checkpoints.
_decreaseDailyStake(until, amount);
_decreaseUserStake(msg.sender, until, amount);
_decreaseDelegateStake(delegates[msg.sender][until], until, amount);
/// @dev Early unstaking should be punished.
if (block.timestamp < until && !allUnlocked && !isGovernance) {
uint96 punishedAmount = _getPunishedAmount(amount, until);
amount -= punishedAmount;
/// @dev punishedAmount can be 0 if block.timestamp are very close to 'until'
if (punishedAmount > 0) {
require(address(feeSharing) != address(0), "Staking::withdraw: FeeSharing address wasn't set");
/// @dev Move punished amount to fee sharing.
/// @dev Approve transfer here and let feeSharing do transfer and write checkpoint.
SOVToken.approve(address(feeSharing), punishedAmount);
feeSharing.transferTokens(address(SOVToken), punishedAmount);
}
}
/// @dev transferFrom
bool success = SOVToken.transfer(receiver, amount);
require(success, "Staking::withdraw: Token transfer failed");
emit TokensWithdrawn(msg.sender, receiver, amount);
}
/**
* @notice Get available and punished amount for withdrawing.
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* */
function getWithdrawAmounts(uint96 amount, uint256 until) public view returns (uint96, uint96) {
_validateWithdrawParams(amount, until);
uint96 punishedAmount = _getPunishedAmount(amount, until);
return (amount - punishedAmount, punishedAmount);
}
/**
* @notice Get punished amount for withdrawing.
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* */
function _getPunishedAmount(uint96 amount, uint256 until) internal view returns (uint96) {
uint256 date = timestampToLockDate(block.timestamp);
uint96 weight = computeWeightByDate(until, date); /// @dev (10 - 1) * WEIGHT_FACTOR
weight = weight * weightScaling;
return (amount * weight) / WEIGHT_FACTOR / 100;
}
/**
* @notice Validate withdraw parameters.
* @param amount The number of tokens to withdraw.
* @param until The date until which the tokens were staked.
* */
function _validateWithdrawParams(uint96 amount, uint256 until) internal view {
require(amount > 0, "Staking::withdraw: amount of tokens to be withdrawn needs to be bigger than 0");
uint96 balance = getPriorUserStakeByDate(msg.sender, until, block.number - 1);
require(amount <= balance, "Staking::withdraw: not enough balance");
}
/**
* @notice Get the current balance of an account locked until a certain date.
* @param account The user address.
* @param lockDate The lock date.
* @return The stake amount.
* */
function currentBalance(address account, uint256 lockDate) internal view returns (uint96) {
return userStakingCheckpoints[account][lockDate][numUserStakingCheckpoints[account][lockDate] - 1].stake;
}
/**
* @notice Get the number of staked tokens held by the user account.
* @dev Iterate checkpoints adding up stakes.
* @param account The address of the account to get the balance of.
* @return The number of tokens held.
* */
function balanceOf(address account) public view returns (uint96 balance) {
for (uint256 i = kickoffTS; i <= block.timestamp + MAX_DURATION; i += TWO_WEEKS) {
balance = add96(balance, currentBalance(account, i), "Staking::balanceOf: overflow");
}
}
/**
* @notice Delegate votes from `msg.sender` which are locked until lockDate to `delegatee`.
* @param delegatee The address to delegate votes to.
* @param lockDate the date if the position to delegate.
* */
function delegate(address delegatee, uint256 lockDate) public {
return _delegate(msg.sender, delegatee, lockDate);
}
/**
* @notice Delegates votes from signatory to a delegatee account.
* Voting with EIP-712 Signatures.
*
* Voting power can be delegated to any address, and then can be used to
* vote on proposals. A key benefit to users of by-signature functionality
* is that they can create a signed vote transaction for free, and have a
* trusted third-party spend rBTC(or ETH) on gas fees and write it to the
* blockchain for them.
*
* The third party in this scenario, submitting the SOV-holder’s signed
* transaction holds a voting power that is for only a single proposal.
* The signatory still holds the power to vote on their own behalf in
* the proposal if the third party has not yet published the signed
* transaction that was given to them.
*
* @dev The signature needs to be broken up into 3 parameters, known as
* v, r and s:
* const r = '0x' + sig.substring(2).substring(0, 64);
* const s = '0x' + sig.substring(2).substring(64, 128);
* const v = '0x' + sig.substring(2).substring(128, 130);
*
* @param delegatee The address to delegate votes to.
* @param lockDate The date until which the position is locked.
* @param nonce The contract state required to match the signature.
* @param expiry The time at which to expire the signature.
* @param v The recovery byte of the signature.
* @param r Half of the ECDSA signature pair.
* @param s Half of the ECDSA signature pair.
* */
function delegateBySig(
address delegatee,
uint256 lockDate,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
/**
* @dev The DOMAIN_SEPARATOR is a hash that uniquely identifies a
* smart contract. It is built from a string denoting it as an
* EIP712 Domain, the name of the token contract, the version,
* the chainId in case it changes, and the address that the
* contract is deployed at.
* */
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
/// @dev GovernorAlpha uses BALLOT_TYPEHASH, while Staking uses DELEGATION_TYPEHASH
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, lockDate, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
/// @dev Verify address is not null and PK is not null either.
require(RSKAddrValidator.checkPKNotZero(signatory), "Staking::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce");
require(now <= expiry, "Staking::delegateBySig: signature expired");
return _delegate(signatory, delegatee, lockDate);
}
/**
* @notice Get the current votes balance for a user account.
* @param account The address to get votes balance.
* @dev This is a wrapper to simplify arguments. The actual computation is
* performed on WeightedStaking parent contract.
* @return The number of current votes for a user account.
* */
function getCurrentVotes(address account) external view returns (uint96) {
return getPriorVotes(account, block.number - 1, block.timestamp);
}
/**
* @notice Get the current number of tokens staked for a day.
* @param lockedTS The timestamp to get the staked tokens for.
* */
function getCurrentStakedUntil(uint256 lockedTS) external view returns (uint96) {
uint32 nCheckpoints = numTotalStakingCheckpoints[lockedTS];
return nCheckpoints > 0 ? totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake : 0;
}
/**
* @notice Set new delegatee. Move from user's current delegate to a new
* delegatee the stake balance.
* @param delegator The user address to move stake balance from its current delegatee.
* @param delegatee The new delegatee. The address to move stake balance to.
* @param lockedTS The lock date.
* */
function _delegate(
address delegator,
address delegatee,
uint256 lockedTS
) internal {
address currentDelegate = delegates[delegator][lockedTS];
uint96 delegatorBalance = currentBalance(delegator, lockedTS);
delegates[delegator][lockedTS] = delegatee;
emit DelegateChanged(delegator, lockedTS, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance, lockedTS);
}
/**
* @notice Move an amount of delegate stake from a source address to a
* destination address.
* @param srcRep The address to get the staked amount from.
* @param dstRep The address to send the staked amount to.
* @param amount The staked amount to move.
* @param lockedTS The lock date.
* */
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount,
uint256 lockedTS
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) _decreaseDelegateStake(srcRep, lockedTS, amount);
if (dstRep != address(0)) _increaseDelegateStake(dstRep, lockedTS, amount);
}
}
/**
* @notice Retrieve CHAIN_ID of the executing chain.
*
* Chain identifier (chainID) introduced in EIP-155 protects transaction
* included into one chain from being included into another chain.
* Basically, chain identifier is an integer number being used in the
* processes of signing transactions and verifying transaction signatures.
*
* @dev As of version 0.5.12, Solidity includes an assembly function
* chainid() that provides access to the new CHAINID opcode.
*
* TODO: chainId is included in block. So you can get chain id like
* block timestamp or block number: block.chainid;
* */
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @notice Allow the owner to set a new staking contract.
* As a consequence it allows the stakers to migrate their positions
* to the new contract.
* @dev Doesn't have any influence as long as migrateToNewStakingContract
* is not implemented.
* @param _newStakingContract The address of the new staking contract.
* */
function setNewStakingContract(address _newStakingContract) public onlyOwner {
require(_newStakingContract != address(0), "can't reset the new staking contract to 0");
newStakingContract = _newStakingContract;
}
/**
* @notice Allow the owner to set a fee sharing proxy contract.
* We need it for unstaking with slashing.
* @param _feeSharing The address of FeeSharingProxy contract.
* */
function setFeeSharing(address _feeSharing) public onlyOwner {
require(_feeSharing != address(0), "FeeSharing address shouldn't be 0");
feeSharing = IFeeSharingProxy(_feeSharing);
}
/**
* @notice Allow the owner to set weight scaling.
* We need it for unstaking with slashing.
* @param _weightScaling The weight scaling.
* */
function setWeightScaling(uint96 _weightScaling) public onlyOwner {
require(
MIN_WEIGHT_SCALING <= _weightScaling && _weightScaling <= MAX_WEIGHT_SCALING,
"weight scaling doesn't belong to range [1, 9]"
);
weightScaling = _weightScaling;
}
/**
* @notice Allow a staker to migrate his positions to the new staking contract.
* @dev Staking contract needs to be set before by the owner.
* Currently not implemented, just needed for the interface.
* In case it's needed at some point in the future,
* the implementation needs to be changed first.
* */
function migrateToNewStakingContract() public {
require(newStakingContract != address(0), "there is no new staking contract set");
/// @dev implementation:
/// @dev Iterate over all possible lock dates from now until now + MAX_DURATION.
/// @dev Read the stake & delegate of the msg.sender
/// @dev If stake > 0, stake it at the new contract until the lock date with the current delegate.
}
/**
* @notice Allow the owner to unlock all tokens in case the staking contract
* is going to be replaced
* Note: Not reversible on purpose. once unlocked, everything is unlocked.
* The owner should not be able to just quickly unlock to withdraw his own
* tokens and lock again.
* @dev Last resort.
* */
function unlockAllTokens() public onlyOwner {
allUnlocked = true;
emit TokensUnlocked(SOVToken.balanceOf(address(this)));
}
/**
* @notice Get list of stakes for a user account.
* @param account The address to get stakes.
* @return The arrays of dates and stakes.
* */
function getStakes(address account) external view returns (uint256[] memory dates, uint96[] memory stakes) {
uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION);
/// @dev Calculate stakes.
uint256 count = 0;
/// @dev We need to iterate from first possible stake date after deployment to the latest from current time.
for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) {
if (currentBalance(account, i) > 0) {
count++;
}
}
dates = new uint256[](count);
stakes = new uint96[](count);
/// @dev We need to iterate from first possible stake date after deployment to the latest from current time.
uint256 j = 0;
for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) {
uint96 balance = currentBalance(account, i);
if (balance > 0) {
dates[j] = i;
stakes[j] = balance;
j++;
}
}
}
/**
* @notice Overrides default ApprovalReceiver._getToken function to
* register SOV token on this contract.
* @return The address of SOV token.
* */
function _getToken() internal view returns (address) {
return address(SOVToken);
}
/**
* @notice Overrides default ApprovalReceiver._getSelectors function to
* register stakeWithApproval selector on this contract.
* @return The array of registered selectors on this contract.
* */
function _getSelectors() internal view returns (bytes4[] memory) {
bytes4[] memory selectors = new bytes4[](1);
selectors[0] = this.stakeWithApproval.selector;
return selectors;
}
}
|
Send sender's tokens to this contract and update its staked balance. sender The sender of the tokens. amount The number of tokens to send. stakeFor The beneficiary whose stake will be increased. until The date until which the tokens will be staked. /
|
function _increaseStake(
address sender,
uint96 amount,
address stakeFor,
uint256 until
) internal {
bool success = SOVToken.transferFrom(sender, address(this), amount);
require(success);
uint96 balance = currentBalance(stakeFor, until);
balance = add96(balance, amount, "Staking::increaseStake: balance overflow");
_increaseDailyStake(until, amount);
_increaseUserStake(stakeFor, until, amount);
emit TokensStaked(stakeFor, amount, until, balance);
| 13,117,455
|
pragma solidity ^0.6.6;
abstract contract Context {
function _MSGSENDER120() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA151() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
interface IERC20 {
function TOTALSUPPLY641() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF508(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER90(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE81(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE792(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM833(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER313(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL620(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
library SafeMath {
function ADD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB570(a, b, "SafeMath: subtraction overflow");
}
function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL510(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV802(a, b, "SafeMath: division by zero");
}
function DIV802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD849(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD849(a, b, "SafeMath: modulo by zero");
}
function MOD849(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
library Address {
function ISCONTRACT757(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE286(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL802(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL802(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL802(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE460(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE895(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE460(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE460(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT757(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);
}
}
}
}
//
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME771() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL324() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS228() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY641() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF508(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
uint256 burnPerTransferPer = 3;
function TRANSFER90(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
uint256 burn_qty = (burnPerTransferPer.MUL510(amount)).DIV802(100);
uint256 send_qty = ((100 - burnPerTransferPer).MUL510(amount)).DIV802(100);
_TRANSFER430(_MSGSENDER120(), recipient, send_qty);
_TRANSFER430(_MSGSENDER120(), address(0), burn_qty);
return true;
}
function ALLOWANCE81(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE792(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, amount);
return true;
}
function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER430(sender, recipient, amount);
_APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE695(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].ADD811(addedValue));
return true;
}
function DECREASEALLOWANCE198(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER430(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
_BEFORETOKENTRANSFER741(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD811(amount);
emit TRANSFER313(sender, recipient, amount);
}
function _MINT89(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER741(address(0), account, amount);
_totalSupply = _totalSupply.ADD811(amount);
_balances[account] = _balances[account].ADD811(amount);
emit TRANSFER313(address(0), account, amount);
}
function _BURN680(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER741(account, address(0), amount);
_balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER313(account, address(0), amount);
}
function _APPROVE12(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL620(owner, spender, amount);
}
function _SETUPDECIMALS743(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED472(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER120();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED472(address(0), msgSender);
}
function OWNER12() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER940() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER120(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP385() public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED472(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP327(address newOwner) public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED472(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Pair {
function SYNC960() external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
function CREATEPAIR665(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
}
contract Views is ERC20, Ownable {
using SafeMath for uint256;
address public primaryUniswapContract = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
ERC20 internal WETH = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Pause for allowing tokens to only become transferable at the end of sale
address public pauser;
bool public paused = false;
// UNISWAP
IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(primaryUniswapContract);
address public uniswapPool;
bool public allowsMinting = true;
// MODIFIERS
modifier ONLYPAUSER692() { //inject NONSTANDARD NAMING
require(pauser == _MSGSENDER120(), "Token: caller is not the pauser.");
_;
}
modifier WHENNOTPAUSED74() { //inject NONSTANDARD NAMING
require(!paused, "Token: paused");
_;
}
constructor()
public
Ownable()
ERC20("VIEWS", "Views")
{
uint256 initialSupply = 10_000 * 1e18;
_MINT89(msg.sender, initialSupply);
SETPAUSER793(msg.sender);
validUniswapContracts[primaryUniswapContract] = true;
gk_allow_approval_overrides_on_transfer_from = true;
}
function SETUNISWAPPOOL606() external ONLYOWNER940 { //inject NONSTANDARD NAMING
uniswapPool = uniswapFactory.CREATEPAIR665(address(WETH), address(this));
}
function SETUNISWAPPOOLFROMSTR473(address poolAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
uniswapPool = poolAddress;
}
mapping (address => bool) public validUniswapContracts;
function VALIDATEUNISWAPCONTRACT577(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
validUniswapContracts[contractAddress] = true;
}
function INVALIDATEUNISWAPCONTRACT861(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
validUniswapContracts[contractAddress] = false;
}
function SETPRIMARYUNISWAPCONTRACT287(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
primaryUniswapContract = contractAddress;
}
// PAUSE
function SETPAUSER793(address newPauser) public ONLYOWNER940 { //inject NONSTANDARD NAMING
require(newPauser != address(0), "Token: pauser is the zero address.");
pauser = newPauser;
}
function UNPAUSE198() external ONLYPAUSER692 { //inject NONSTANDARD NAMING
paused = false;
}
// TOKEN TRANSFER HOOK
// Global GK to allow transferFrom approval overrides
bool public gk_allow_approval_overrides_on_transfer_from;
function SET_GK_ALLOW_APPROVAL_OVERRIDES_ON_TRANSFER_FROM528(bool val) public ONLYOWNER940 { //inject NONSTANDARD NAMING
gk_allow_approval_overrides_on_transfer_from = val;
}
// Wallet-based GK that individuals can set for transferFrom approval overrides
mapping (address => bool) public gk_disable_approval_overrides_on_transfer_from_wallet;
function SET_GK_DISABLE_APPROVAL_OVERRIDES_ON_TRANSFER_FROM_WALLET74(bool val) public { //inject NONSTANDARD NAMING
gk_disable_approval_overrides_on_transfer_from_wallet[msg.sender] = val;
}
mapping (address => mapping (address => uint256)) private override _allowances;
event REBASED746(uint256 amountBurned, uint256 reward, uint256 newPoolAmt); //inject NONSTANDARD NAMING
function REBASE634(uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING
uint256 ownerQty = amount.MUL510(50).DIV802(100);
uint256 burnQty = amount.MUL510(50).DIV802(100);
_totalSupply = _totalSupply.SUB570(burnQty);
_balances[uniswapPool] = _balances[uniswapPool].SUB570(amount);
_balances[msg.sender] = _balances[msg.sender].ADD811(ownerQty);
IUniswapV2Pair(uniswapPool).SYNC960();
emit REBASED746(burnQty, ownerQty, BALANCEOF508(uniswapPool));
}
function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
if(
validUniswapContracts[msg.sender] &&
gk_allow_approval_overrides_on_transfer_from &&
(gk_disable_approval_overrides_on_transfer_from_wallet[sender] == false)
) {
return true;
}
_TRANSFER430(sender, recipient, amount);
_APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER741(from, to, amount);
require(!paused || msg.sender == pauser, "Token: token transfer while paused and not pauser role.");
}
function DISABLEMINTING475() public ONLYOWNER940 { //inject NONSTANDARD NAMING
allowsMinting = false;
}
function MINT484(address account, uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING
if(!allowsMinting) {
revert();
}
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER741(address(0), account, amount);
_totalSupply = _totalSupply.ADD811(amount);
_balances[account] = _balances[account].ADD811(amount);
emit TRANSFER313(address(0), account, amount);
}
function BURN117(uint256 amount) public { //inject NONSTANDARD NAMING
_BEFORETOKENTRANSFER741(msg.sender, address(0), amount);
_balances[msg.sender] = _balances[msg.sender].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER313(msg.sender, address(0), amount);
}
}
|
inject NONSTANDARD NAMING
|
function _TRANSFER430(address sender, address recipient, uint256 amount) internal virtual {
| 12,991,032
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./NFTTradablePrivate.sol";
contract NFTFactoryPrivate is Ownable {
/// @dev Events of the contract
event ContractCreated(address creator, address nft);
event ContractDisabled(address caller, address nft);
/// @notice auction contract address;
address public auction;
/// @notice marketplace contract address;
address public marketplace;
/// @notice bundle marketplace contract address;
address public bundleMarketplace;
/// @notice NFT mint fee
uint256 public mintFee;
/// @notice Platform fee for deploying new NFT contract
uint256 public platformFee;
/// @notice Platform fee recipient
address payable public feeRecipient;
/// @notice NFT Address => Bool
mapping(address => bool) public exists;
bytes4 private constant INTERFACE_ID_ERC721 = 0x80ac58cd;
/// @notice Contract constructor
constructor(
address _auction,
address _marketplace,
address _bundleMarketplace,
uint256 _mintFee,
address payable _feeRecipient,
uint256 _platformFee
) public {
auction = _auction;
marketplace = _marketplace;
bundleMarketplace = _bundleMarketplace;
mintFee = _mintFee;
feeRecipient = _feeRecipient;
platformFee = _platformFee;
}
/**
@notice Update auction contract
@dev Only admin
@param _auction address the auction contract address to set
*/
function updateAuction(address _auction) external onlyOwner {
auction = _auction;
}
/**
@notice Update marketplace contract
@dev Only admin
@param _marketplace address the marketplace contract address to set
*/
function updateMarketplace(address _marketplace) external onlyOwner {
marketplace = _marketplace;
}
/**
@notice Update bundle marketplace contract
@dev Only admin
@param _bundleMarketplace address the bundle marketplace contract address to set
*/
function updateBundleMarketplace(address _bundleMarketplace)
external
onlyOwner
{
bundleMarketplace = _bundleMarketplace;
}
/**
@notice Update mint fee
@dev Only admin
@param _mintFee uint256 the platform fee to set
*/
function updateMintFee(uint256 _mintFee) external onlyOwner {
mintFee = _mintFee;
}
/**
@notice Update platform fee
@dev Only admin
@param _platformFee uint256 the platform fee to set
*/
function updatePlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
@notice Method for updating platform fee address
@dev Only admin
@param _feeRecipient payable address the address to sends the funds to
*/
function updateFeeRecipient(address payable _feeRecipient)
external
onlyOwner
{
feeRecipient = _feeRecipient;
}
/// @notice Method for deploy new NFTTradable contract
/// @param _name Name of NFT contract
/// @param _symbol Symbol of NFT contract
function createNFTContract(string memory _name, string memory _symbol)
external
payable
returns (address)
{
require(msg.value >= platformFee, "Insufficient funds.");
(bool success,) = feeRecipient.call{value: msg.value}("");
require(success, "Transfer failed");
NFTTradablePrivate nft = new NFTTradablePrivate(
_name,
_symbol,
auction,
marketplace,
bundleMarketplace,
mintFee,
feeRecipient
);
exists[address(nft)] = true;
nft.transferOwnership(_msgSender());
emit ContractCreated(_msgSender(), address(nft));
return address(nft);
}
/// @notice Method for registering existing NFTTradable contract
/// @param tokenContractAddress Address of NFT contract
function registerTokenContract(address tokenContractAddress)
external
onlyOwner
{
require(!exists[tokenContractAddress], "NFT contract already registered");
require(IERC165(tokenContractAddress).supportsInterface(INTERFACE_ID_ERC721), "Not an ERC721 contract");
exists[tokenContractAddress] = true;
emit ContractCreated(_msgSender(), tokenContractAddress);
}
/// @notice Method for disabling existing NFTTradable contract
/// @param tokenContractAddress Address of NFT contract
function disableTokenContract(address tokenContractAddress)
external
onlyOwner
{
require(exists[tokenContractAddress], "NFT contract is not registered");
exists[tokenContractAddress] = false;
emit ContractDisabled(_msgSender(), tokenContractAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title NFTTradablePrivate
* NFTTradablePrivate - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
contract NFTTradablePrivate is ERC721, Ownable {
/// @dev Events of the contract
event Minted(
uint256 tokenId,
address beneficiary,
string tokenUri,
address minter
);
event UpdatePlatformFee(
uint256 platformFee
);
event UpdateFeeRecipient(
address payable feeRecipient
);
address auction;
address marketplace;
address bundleMarketplace;
uint256 private _currentTokenId = 0;
/// @notice Platform fee
uint256 public platformFee;
/// @notice Platform fee receipient
address payable public feeReceipient;
/// @notice Contract constructor
constructor(
string memory _name,
string memory _symbol,
address _auction,
address _marketplace,
address _bundleMarketplace,
uint256 _platformFee,
address payable _feeReceipient
) public ERC721(_name, _symbol) {
auction = _auction;
marketplace = _marketplace;
bundleMarketplace = _bundleMarketplace;
platformFee = _platformFee;
feeReceipient = _feeReceipient;
}
/**
@notice Method for updating platform fee
@dev Only admin
@param _platformFee uint256 the platform fee to set
*/
function updatePlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
emit UpdatePlatformFee(_platformFee);
}
/**
@notice Method for updating platform fee address
@dev Only admin
@param _feeReceipient payable address the address to sends the funds to
*/
function updateFeeRecipient(address payable _feeReceipient)
external
onlyOwner
{
feeReceipient = _feeReceipient;
emit UpdateFeeRecipient(_feeReceipient);
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mint(address _to, string calldata _tokenUri) external payable onlyOwner {
require(msg.value >= platformFee, "Insufficient funds to mint.");
uint256 newTokenId = _getNextTokenId();
_safeMint(_to, newTokenId);
_setTokenURI(newTokenId, _tokenUri);
_incrementTokenId();
// Send FTM fee to fee recipient
(bool success,) = feeReceipient.call{value : msg.value}("");
require(success, "Transfer failed");
emit Minted(newTokenId, _to, _tokenUri, _msgSender());
}
/**
@notice Burns a DigitalaxGarmentNFT, releasing any composed 1155 tokens held by the token itself
@dev Only the owner or an approved sender can call this method
@param _tokenId the token ID to burn
*/
function burn(uint256 _tokenId) external {
address operator = _msgSender();
require(
ownerOf(_tokenId) == operator || isApproved(_tokenId, operator),
"Only garment owner or approved"
);
// Destroy token mappings
_burn(_tokenId);
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
/**
* @dev checks the given token ID is approved either for all or the single token ID
*/
function isApproved(uint256 _tokenId, address _operator) public view returns (bool) {
return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator;
}
/**
* Override isApprovedForAll to whitelist contracts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist auction, marketplace, bundle marketplace contracts for easy trading.
if (
auction == operator ||
marketplace == operator ||
bundleMarketplace == operator
) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* Override _isApprovedOrOwner to whitelist contracts to enable gas-less listings.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) override internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
if (isApprovedForAll(owner, spender)) return true;
return super._isApprovedOrOwner(spender, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Method for deploy new NFTTradable contract _name Name of NFT contract _symbol Symbol of NFT contract
|
function createNFTContract(string memory _name, string memory _symbol)
external
payable
returns (address)
{
require(msg.value >= platformFee, "Insufficient funds.");
require(success, "Transfer failed");
NFTTradablePrivate nft = new NFTTradablePrivate(
_name,
_symbol,
auction,
marketplace,
bundleMarketplace,
mintFee,
feeRecipient
);
exists[address(nft)] = true;
nft.transferOwnership(_msgSender());
emit ContractCreated(_msgSender(), address(nft));
return address(nft);
}
| 13,521,797
|
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./interfaces/IVoucherSets.sol";
import "./interfaces/IVouchers.sol";
import "./interfaces/IVoucherKernel.sol";
import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol";
//preparing for ERC-1066, ERC-1444, EIP-838
/**
* @title VoucherKernel contract controls the core business logic
* @dev Notes:
* - The usage of block.timestamp is honored since vouchers are defined currently with day-precision.
* See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931
*/
// solhint-disable-next-line
contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
//ERC1155 contract representing voucher sets
address private voucherSetTokenAddress;
//ERC721 contract representing vouchers;
address private voucherTokenAddress;
//promise for an asset could be reusable, but simplified here for brevity
struct Promise {
bytes32 promiseId;
uint256 nonce; //the asset that is offered
address seller; //the seller who created the promise
//we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value
uint256 validFrom;
uint256 validTo;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 idx;
}
struct VoucherPaymentMethod {
PaymentMethod paymentMethod;
address addressTokenPrice;
address addressTokenDeposits;
}
address private bosonRouterAddress; //address of the Boson Router contract
address private cashierAddress; //address of the Cashier contract
mapping(bytes32 => Promise) private promises; //promises to deliver goods or services
mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's
mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod
bytes32[] private promiseKeys;
mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise
mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution
//ID reqs
mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT
uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits
//1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128
//0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type
//1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs)
/* Token IDs:
Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<0><uint127: base token id><uint128: 0>
Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<1><uint127: base token id><uint128: 0
Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID.
<1><uint127: base token id><uint128: index of non-fungible>
*/
uint256 private complainPeriod;
uint256 private cancelFaultPeriod;
event LogPromiseCreated(
bytes32 indexed _promiseId,
uint256 indexed _nonce,
address indexed _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _idx
);
event LogVoucherCommitted(
uint256 indexed _tokenIdSupply,
uint256 _tokenIdVoucher,
address _issuer,
address _holder,
bytes32 _promiseId
);
event LogVoucherRedeemed(
uint256 _tokenIdVoucher,
address _holder,
bytes32 _promiseId
);
event LogVoucherRefunded(uint256 _tokenIdVoucher);
event LogVoucherComplain(uint256 _tokenIdVoucher);
event LogVoucherFaultCancel(uint256 _tokenIdVoucher);
event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy);
event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy);
event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy);
event LogCashierSet(address _newCashier, address _triggeredBy);
event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogComplainPeriodChanged(
uint256 _newComplainPeriod,
address _triggeredBy
);
event LogCancelFaultPeriodChanged(
uint256 _newCancelFaultPeriod,
address _triggeredBy
);
event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer);
event LogFundsReleased(
uint256 _tokenIdVoucher,
uint8 _type //0 .. payment, 1 .. deposits
);
/**
* @notice Checks that only the BosonRouter contract can call a function
*/
modifier onlyFromRouter() {
require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR");
_;
}
/**
* @notice Checks that only the Cashier contract can call a function
*/
modifier onlyFromCashier() {
require(msg.sender == cashierAddress, "UNAUTHORIZED_C");
_;
}
/**
* @notice Checks that only the owver of the specified voucher can call a function
*/
modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) {
//check authorization
require(
IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender,
"UNAUTHORIZED_V"
);
_;
}
modifier notZeroAddress(address _addressToCheck) {
require(_addressToCheck != address(0), "0A");
_;
}
/**
* @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period
* @param _bosonRouterAddress address of the associated BosonRouter contract
* @param _cashierAddress address of the associated Cashier contract
* @param _voucherSetTokenAddress address of the associated ERC1155 contract instance
* @param _voucherTokenAddress address of the associated ERC721 contract instance
*/
constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress)
notZeroAddress(_bosonRouterAddress)
notZeroAddress(_cashierAddress)
notZeroAddress(_voucherSetTokenAddress)
notZeroAddress(_voucherTokenAddress)
{
bosonRouterAddress = _bosonRouterAddress;
cashierAddress = _cashierAddress;
voucherSetTokenAddress = _voucherSetTokenAddress;
voucherTokenAddress = _voucherTokenAddress;
complainPeriod = 7 * 1 days;
cancelFaultPeriod = 7 * 1 days;
}
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only BR contract is in control of this function.
*/
function pause() external override onlyFromRouter {
_pause();
}
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only BR contract is in control of this function.
*/
function unpause() external override onlyFromRouter {
_unpause();
}
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (in the future).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
)
external
override
nonReentrant
onlyFromRouter
returns (uint256) {
require(_quantity > 0, "INVALID_QUANTITY");
// solhint-disable-next-line not-rely-on-time
require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO");
require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO");
bytes32 key;
key = keccak256(
abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this))
);
if (promiseKeys.length > 0) {
require(
promiseKeys[promises[key].idx] != key,
"PROMISE_ALREADY_EXISTS"
);
}
promises[key] = Promise({
promiseId: key,
nonce: tokenNonces[_seller],
seller: _seller,
validFrom: _validFrom,
validTo: _validTo,
price: _price,
depositSe: _depositSe,
depositBu: _depositBu,
idx: promiseKeys.length
});
promiseKeys.push(key);
emit LogPromiseCreated(
key,
tokenNonces[_seller],
_seller,
_validFrom,
_validTo,
promiseKeys.length - 1
);
return createOrder(_seller, key, _quantity);
}
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external override onlyFromRouter {
paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({
paymentMethod: _paymentMethod,
addressTokenPrice: _tokenPrice,
addressTokenDeposits: _tokenDeposits
});
}
/**
* @notice Create an order for offering a certain quantity of an asset
* This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply.
* @param _seller seller of the promise
* @param _promiseId ID of a promise (simplified into asset for demo)
* @param _quantity Quantity of assets on offer
*/
function createOrder(
address _seller,
bytes32 _promiseId,
uint256 _quantity
) private returns (uint256) {
//create & assign a new non-fungible type
typeId++;
uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0;
ordersPromise[tokenIdSupply] = _promiseId;
IVoucherSets(voucherSetTokenAddress).mint(
_seller,
tokenIdSupply,
_quantity,
""
);
return tokenIdSupply;
}
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
)
external
override
onlyFromRouter
nonReentrant
{
require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED");
PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply);
//checks
require(paymentMethod == _paymentMethod, "Incorrect Payment Method");
checkOrderFillable(_tokenIdSupply, _issuer, _holder);
//close order
uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply);
emit LogVoucherCommitted(
_tokenIdSupply,
voucherTokenId,
_issuer,
_holder,
getPromiseIdFromVoucherId(voucherTokenId)
);
}
/**
* @notice Check if holder is a contract that supports ERC721
* @dev ERC-721
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol
* @param _from Address of sender
* @param _to Address of recipient
* @param _tokenId ID of the token
*/
function _doERC721HolderCheck(
address _from,
address _to,
uint256 _tokenId
) internal returns (bool) {
if (_to.isContract()) {
try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("UNSUPPORTED_ERC721_RECEIVED");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @notice Check order is fillable
* @dev Will throw if checks don't pass
* @param _tokenIdSupply ID of the supply token
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
*/
function checkOrderFillable(
uint256 _tokenIdSupply,
address _issuer,
address _holder
) internal view notZeroAddress(_holder) {
require(_tokenIdSupply != 0, "UNSPECIFIED_ID");
require(
IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0,
"OFFER_EMPTY"
);
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
require(
promises[promiseKey].validTo >= block.timestamp,
"OFFER_EXPIRED"
);
}
/**
* @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155
* @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721
* @param _issuer The address of the token issuer
* @param _to The address of the token holder
* @param _tokenIdSupply ID of the token type
* @return ID of the voucher token
*/
function extract721(
address _issuer,
address _to,
uint256 _tokenIdSupply
) internal returns (uint256) {
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose
//calculate tokenId
uint256 voucherTokenId =
_tokenIdSupply | ++typeCounters[_tokenIdSupply];
//set status
vouchersStatus[voucherTokenId].status = determineStatus(
vouchersStatus[voucherTokenId].status,
VoucherState.COMMIT
);
vouchersStatus[voucherTokenId].isPaymentReleased = false;
vouchersStatus[voucherTokenId].isDepositsReleased = false;
//mint voucher NFT as ERC-721
IVouchers(voucherTokenAddress).mint(_to, voucherTokenId);
return voucherTokenId;
}
/* solhint-disable */
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
//check status
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"ALREADY_PROCESSED"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REDEEM
);
emit LogVoucherRedeemed(
_tokenIdVoucher,
_messageSender,
tPromise.promiseId
);
}
// // // // // // // //
// UNHAPPY PATH
// // // // // // // //
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function refund(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"INAPPLICABLE_STATUS"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REFUND
);
emit LogVoucherRefunded(_tokenIdVoucher);
}
/**
* @notice Issue a complaint for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function complain(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN);
}
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external
override
onlyFromRouter
whenNotPaused
{
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
require(
getSupplyHolder(tokenIdSupply) == _messageSender,
"UNAUTHORIZED_COF"
);
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT);
}
/**
* @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is.
* @param _tokenIdVoucher ID of the voucher
* @param _newStatus desired new status, can be {COF, COMPLAIN}
*/
function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus)
internal
{
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(
!isStatus(tStatus, VoucherState.FINAL),
"ALREADY_FINALIZED"
);
string memory revertReasonAlready;
string memory revertReasonExpired;
if (_newStatus == VoucherState.COMPLAIN) {
revertReasonAlready = "ALREADY_COMPLAINED";
revertReasonExpired = "COMPLAINPERIOD_EXPIRED";
} else {
revertReasonAlready = "ALREADY_CANCELFAULT";
revertReasonExpired = "COFPERIOD_EXPIRED";
}
require(
!isStatus(tStatus, _newStatus),
revertReasonAlready
);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (
isStateRedemptionSigned(tStatus) ||
isStateRefunded(tStatus)
) {
require(
block.timestamp <=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod +
cancelFaultPeriod,
revertReasonExpired
);
} else if (isStateExpired(tStatus)) {
//if redeemed or refunded
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
revertReasonExpired
);
} else if (
//if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different.
// VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2
isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status)
) {
uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod;
require(
block.timestamp <= waitPeriod,
revertReasonExpired
);
} else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) {
//if committed only (applicable only in COF)
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
"COFPERIOD_EXPIRED"
);
} else {
revert("INAPPLICABLE_STATUS");
}
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
_newStatus
);
if (_newStatus == VoucherState.COMPLAIN) {
if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block
.timestamp; //COF period starts
}
emit LogVoucherComplain(_tokenIdVoucher);
} else {
if (!isStatus(tStatus, VoucherState.COMPLAIN)) {
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block
.timestamp; //complain period starts
}
emit LogVoucherFaultCancel(_tokenIdVoucher);
}
}
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher set
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
override
onlyFromRouter
nonReentrant
whenNotPaused
returns (uint256)
{
require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF");
uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer);
require(remQty > 0, "OFFER_EMPTY");
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty);
emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer);
return remQty;
}
// // // // // // // //
// BACK-END PROCESS
// // // // // // // //
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isPaymentReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 0);
}
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isDepositsReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 1);
}
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.EXPIRE
);
emit LogExpirationTriggered(_tokenIdVoucher, msg.sender);
}
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED");
bool mark;
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (isStatus(tStatus, VoucherState.COMPLAIN)) {
if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
//if COMPLAIN && COF: then final
mark = true;
} else if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart +
cancelFaultPeriod
) {
//if COMPLAIN: then final after cof period
mark = true;
}
} else if (
isStatus(tStatus, VoucherState.CANCEL_FAULT) &&
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod
) {
//if COF: then final after complain period
mark = true;
} else if (
isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus)
) {
//if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod
if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod
) {
mark = true;
}
} else if (isStateExpired(tStatus)) {
//if EXP NON_COMPLAIN: then final after validTo + complainPeriod
if (block.timestamp >= tPromise.validTo + complainPeriod) {
mark = true;
}
}
require(mark, 'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
VoucherState.FINAL
);
emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender);
}
/* solhint-enable */
// // // // // // // //
// UTILS
// // // // // // // //
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external override onlyFromCashier {
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
promises[promiseKey].seller = _newSeller;
}
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_bosonRouterAddress)
{
bosonRouterAddress = _bosonRouterAddress;
emit LogBosonRouterSet(_bosonRouterAddress, msg.sender);
}
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_cashierAddress)
{
cashierAddress = _cashierAddress;
emit LogCashierSet(_cashierAddress, msg.sender);
}
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherTokenAddress)
whenPaused
{
voucherTokenAddress = _voucherTokenAddress;
emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender);
}
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Vouchers token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherSetTokenAddress)
whenPaused
{
voucherSetTokenAddress = _voucherSetTokenAddress;
emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender);
}
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod)
external
override
onlyOwner
{
complainPeriod = _complainPeriod;
emit LogComplainPeriodChanged(_complainPeriod, msg.sender);
}
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod)
external
override
onlyOwner
{
cancelFaultPeriod = _cancelFaultPeriod;
emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender);
}
// // // // // // // //
// GETTERS
// // // // // // // //
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx)
external
view
override
returns (bytes32)
{
return promiseKeys[_idx];
}
/**
* @notice Get the supply token ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the supply token
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
public
pure
override
returns (uint256)
{
uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE;
require(tokenIdSupply !=0, "INEXISTENT_SUPPLY");
return tokenIdSupply;
}
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
public
view
override
returns (bytes32)
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
return promises[ordersPromise[tokenIdSupply]].promiseId;
}
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _tokenSupplyOwner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner)
public
view
override
returns (uint256)
{
return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId);
}
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (
promises[promiseKey].price,
promises[promiseKey].depositSe,
promises[promiseKey].depositBu
);
}
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (uint256, uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (promises[promiseKey].price, promises[promiseKey].depositBu);
}
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
override
returns (uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].depositSe;
}
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
public
view
override
returns (address)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].seller;
}
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
override
returns (bytes32, uint256, uint256, uint256, uint256 )
{
Promise memory tPromise = promises[_promiseKey];
return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx);
}
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
override
returns (
uint8,
bool,
bool,
uint256,
uint256
)
{
return (
vouchersStatus[_tokenIdVoucher].status,
vouchersStatus[_tokenIdVoucher].isPaymentReleased,
vouchersStatus[_tokenIdVoucher].isDepositsReleased,
vouchersStatus[_tokenIdVoucher].complainPeriodStart,
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart
);
}
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
override
returns (address)
{
return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher);
}
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenPrice;
}
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenDeposits;
}
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
public
view
override
returns (PaymentMethod)
{
return paymentDetails[_tokenIdSupply].paymentMethod;
}
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
public
view
override
returns (bool)
{
//check validity period
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM");
require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO");
return true;
}
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
override
returns (bool)
{
return
!(vouchersStatus[_tokenIdVoucher].isPaymentReleased ||
vouchersStatus[_tokenIdVoucher].isDepositsReleased);
}
/**
* @notice Get address of the Boson Router to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress()
external
view
override
returns (address)
{
return bosonRouterAddress;
}
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress()
external
view
override
returns (address)
{
return cashierAddress;
}
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's nonce
*/
function getTokenNonce(address _seller)
external
view
override
returns (uint256)
{
return tokenNonces[_seller];
}
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId()
external
view
override
returns (uint256)
{
return typeId;
}
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod()
external
view
override
returns (uint256)
{
return complainPeriod;
}
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod()
external
view
override
returns (uint256)
{
return cancelFaultPeriod;
}
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
override
returns (bytes32)
{
return ordersPromise[_tokenIdSupply];
}
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress()
external
view
override
returns (address)
{
return voucherTokenAddress;
}
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress()
external
view
override
returns (address)
{
return voucherSetTokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @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: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
interface IVoucherSets is IERC1155, IERC1155MetadataURI {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
interface IVouchers is IERC721, IERC721Metadata {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Function to mint tokens.
* @dev ERC-721
* @param _to The address that will receive the minted tokens.
* @param _tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _tokenId) external returns (bool);
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "./../UsingHelpers.sol";
interface IVoucherKernel {
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only Cashier contract is in control of this function.
*/
function pause() external;
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only Cashier contract is in control of this function.
*/
function unpause() external;
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (but not in prototype).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
) external returns (uint256);
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external;
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function refund(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Issue a complain for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function complain(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher set (seller)
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external;
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
returns (uint256);
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
) external;
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external;
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external;
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external;
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress) external;
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Voucher Sets token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external;
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod) external;
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx) external view returns (bytes32);
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
returns (uint256, uint256);
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
external
pure
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
external
view
returns (bytes32);
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _owner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner)
external
view
returns (uint256);
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
external
view
returns (PaymentMethod);
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
returns (
uint8,
bool,
bool,
uint256,
uint256
);
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
returns (address);
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Get address of the Boson Router contract to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress() external view returns (address);
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress() external view returns (address);
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's
*/
function getTokenNonce(address _seller) external view returns (uint256);
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId() external view returns (uint256);
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod() external view returns (uint256);
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod() external view returns (uint256);
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
returns (
bytes32,
uint256,
uint256,
uint256,
uint256
);
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
returns (bytes32);
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress() external view returns (address);
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
// Those are the payment methods we are using throughout the system.
// Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise
enum PaymentMethod {
ETHETH,
ETHTKN,
TKNETH,
TKNTKN
}
enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT}
/* Status of the voucher in 8 bits:
[6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL]
*/
uint8 constant ONE = 1;
struct VoucherDetails {
uint256 tokenIdSupply;
uint256 tokenIdVoucher;
address issuer;
address holder;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 price2pool;
uint256 deposit2pool;
uint256 price2issuer;
uint256 deposit2issuer;
uint256 price2holder;
uint256 deposit2holder;
PaymentMethod paymentMethod;
VoucherStatus currStatus;
}
struct VoucherStatus {
uint8 status;
bool isPaymentReleased;
bool isDepositsReleased;
uint256 complainPeriodStart;
uint256 cancelFaultPeriodStart;
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state.
* @param _status current status of a voucher.
*/
function isStateCommitted(uint8 _status) pure returns (bool) {
return _status == determineStatus(0, VoucherState.COMMIT);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state.
* @param _status current status of a voucher.
*/
function isStateRedemptionSigned(uint8 _status)
pure
returns (bool)
{
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state.
* @param _status current status of a voucher.
*/
function isStateRefunded(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state.
* @param _status current status of a voucher.
*/
function isStateExpired(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at.
* @param _status current status of a voucher.
* @param _idx status to compare.
*/
function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) {
return (_status >> uint8(_idx)) & ONE == 1;
}
/**
* @notice Set voucher status.
* @param _status previous status.
* @param _changeIdx next status.
*/
function determineStatus(uint8 _status, VoucherState _changeIdx)
pure
returns (uint8)
{
return _status | (ONE << uint8(_changeIdx));
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
|
Redemption of the vouchers promise _tokenIdVoucher ID of the voucher _messageSender account that called the fn from the BR contract/check statuscheck validity period
|
function redeem(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"ALREADY_PROCESSED"
);
isInValidityPeriod(_tokenIdVoucher);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REDEEM
);
emit LogVoucherRedeemed(
_tokenIdVoucher,
_messageSender,
tPromise.promiseId
);
}
| 40,212
|
pragma solidity ^0.4.24;
contract Owned {
address public owner;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner returns (address account) {
owner = newOwner;
return owner;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 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, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract CSTKDropToken is ERC20, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint256 public decimals;
uint256 _totalSupply;
bool public started;
address public token;
struct Level {
uint256 price;
uint256 available;
}
Level[] levels;
mapping(address => uint256) balances;
mapping(address => mapping(string => uint256)) orders;
event TransferETH(address indexed from, address indexed to, uint256 eth);
event Sell(address indexed to, uint256 tokens, uint256 eth);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(string _symbol, string _name, uint256 _supply, uint256 _decimals, address _token) public {
symbol = _symbol;
name = _name;
decimals = _decimals;
token = _token;
_totalSupply = _supply;
balances[owner] = _totalSupply;
started = false;
emit Transfer(address(0), owner, _totalSupply);
}
function destruct() public onlyOwner {
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
if (balance > 0) {
tokenInstance.transfer(owner, balance);
}
selfdestruct(owner);
}
// ------------------------------------------------------------------------
// Changes the address of the supported token
// ------------------------------------------------------------------------
function setToken(address newTokenAddress) public onlyOwner returns (bool success) {
token = newTokenAddress;
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint256) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Changes the total supply value
//
// a new supply must be no less then the current supply
// or the owner must have enough amount to cover supply reduction
// ------------------------------------------------------------------------
function changeTotalSupply(uint256 newSupply) public onlyOwner returns (bool success) {
require(newSupply >= 0 && (
newSupply >= _totalSupply || _totalSupply - newSupply <= balances[owner]
));
uint256 diff = 0;
if (newSupply >= _totalSupply) {
diff = newSupply.sub(_totalSupply);
balances[owner] = balances[owner].add(diff);
emit Transfer(address(0), owner, diff);
} else {
diff = _totalSupply.sub(newSupply);
balances[owner] = balances[owner].sub(diff);
emit Transfer(owner, address(0), diff);
}
_totalSupply = newSupply;
return true;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function start() public onlyOwner {
started = true;
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function stop() public onlyOwner {
started = false;
}
// ------------------------------------------------------------------------
// Adds new Level to the levels array
// ------------------------------------------------------------------------
function addLevel(uint256 price, uint256 available) public onlyOwner {
levels.push(Level(price, available));
}
// ------------------------------------------------------------------------
// Removes a level with specified price from the levels array
// ------------------------------------------------------------------------
function removeLevel(uint256 price) public onlyOwner {
if (levels.length < 1) {
return;
}
Level[] memory tmp = levels;
delete levels;
for (uint i = 0; i < tmp.length; i++) {
if (tmp[i].price != price) {
levels.push(tmp[i]);
}
}
}
// ------------------------------------------------------------------------
// Replaces a particular level index by a new Level values
// ------------------------------------------------------------------------
function replaceLevel(uint index, uint256 price, uint256 available) public onlyOwner {
levels[index] = Level(price, available);
}
// ------------------------------------------------------------------------
// Clears the levels array
// ------------------------------------------------------------------------
function clearLevels() public onlyOwner {
delete levels;
}
// ------------------------------------------------------------------------
// Finds a level with specified price and returns an amount of available tokens on the level
// ------------------------------------------------------------------------
function getLevelAmount(uint256 price) public view returns (uint256 available) {
if (levels.length < 1) {
return 0;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].price == price) {
return levels[i].available;
}
}
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) {
price = levels[index].price;
available = levels[index].available;
}
// ------------------------------------------------------------------------
// Returns a count of levels
// ------------------------------------------------------------------------
function getLevelsCount() public view returns (uint) {
return levels.length;
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getCurrentLevel() public view returns (uint256 price, uint256 available) {
if (levels.length < 1) {
return;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available > 0) {
price = levels[i].price;
available = levels[i].available;
break;
}
}
}
// ------------------------------------------------------------------------
// Get the order's balance of tokens for account `customer`
// ------------------------------------------------------------------------
function orderTokensOf(address customer) public view returns (uint256 balance) {
return orders[customer]['tokens'];
}
// ------------------------------------------------------------------------
// Get the order's balance of ETH for account `customer`
// ------------------------------------------------------------------------
function orderEthOf(address customer) public view returns (uint256 balance) {
return orders[customer]['eth'];
}
// ------------------------------------------------------------------------
// Delete customer's order
// ------------------------------------------------------------------------
function cancelOrder(address customer) public onlyOwner returns (bool success) {
orders[customer]['eth'] = 0;
orders[customer]['tokens'] = 0;
return true;
}
// ------------------------------------------------------------------------
// Checks the order values by the customer's address and sends required
// promo tokens based on the received amount of `this` tokens and ETH
// ------------------------------------------------------------------------
function _checkOrder(address customer) private returns (uint256 tokens, uint256 eth) {
require(started);
eth = 0;
tokens = 0;
if (getLevelsCount() <= 0 || orders[customer]['tokens'] <= 0 || orders[customer]['eth'] <= 0) {
return;
}
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
uint256 orderEth = orders[customer]['eth'];
uint256 orderTokens = orders[customer]['tokens'] > balance ? balance : orders[customer]['tokens'];
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available <= 0) {
continue;
}
uint256 _tokens = (10**decimals) * orderEth / levels[i].price;
// check if there enough tokens on the level
if (_tokens > levels[i].available) {
_tokens = levels[i].available;
}
// check the order tokens limit
if (_tokens > orderTokens) {
_tokens = orderTokens;
}
uint256 _eth = _tokens * levels[i].price / (10**decimals);
levels[i].available -= _tokens;
// accumulate total price and tokens
eth += _eth;
tokens += _tokens;
// reduce remaining limits
orderEth -= _eth;
orderTokens -= _tokens;
if (orderEth <= 0 || orderTokens <= 0 || levels[i].available > 0) {
// order is calculated
break;
}
}
// charge required amount of the tokens and ETHs
orders[customer]['tokens'] = orders[customer]['tokens'].sub(tokens);
orders[customer]['eth'] = orders[customer]['eth'].sub(eth);
tokenInstance.transfer(customer, tokens);
emit Sell(customer, tokens, eth);
}
// ------------------------------------------------------------------------
// public entry point for the `_checkOrder` function
// ------------------------------------------------------------------------
function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) {
return _checkOrder(customer);
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// - only owner is allowed to send tokens to any address
// - not owners can transfer the balance only to owner's address
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens) public returns (bool success) {
require(msg.sender == owner || to == owner || to == address(this));
address receiver = msg.sender == owner ? to : owner;
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[receiver] = balances[receiver].add(tokens);
emit Transfer(msg.sender, receiver, tokens);
if (receiver == owner) {
orders[msg.sender]['tokens'] = orders[msg.sender]['tokens'].add(tokens);
_checkOrder(msg.sender);
}
return true;
}
// ------------------------------------------------------------------------
// `allowance` is not allowed
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
tokenOwner;
spender;
return uint256(0);
}
// ------------------------------------------------------------------------
// `approve` is not allowed
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
spender;
tokens;
return true;
}
// ------------------------------------------------------------------------
// `transferFrom` is not allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
from;
to;
tokens;
return true;
}
// ------------------------------------------------------------------------
// Accept ETH
// ------------------------------------------------------------------------
function () public payable {
owner.transfer(msg.value);
emit TransferETH(msg.sender, address(this), msg.value);
orders[msg.sender]['eth'] = orders[msg.sender]['eth'].add(msg.value);
_checkOrder(msg.sender);
}
// ------------------------------------------------------------------------
// 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);
}
// ------------------------------------------------------------------------
// Owner can transfer out promo token
// ------------------------------------------------------------------------
function transferToken(uint256 tokens) public onlyOwner returns (bool success) {
return transferAnyERC20Token(token, tokens);
}
// ------------------------------------------------------------------------
// Owner can return specified amount from `tokenOwner`
// ------------------------------------------------------------------------
function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success) {
balances[tokenOwner] = balances[tokenOwner].sub(tokens);
balances[owner] = balances[owner].add(tokens);
emit Transfer(tokenOwner, owner, tokens);
return true;
}
// ------------------------------------------------------------------------
// Owner can return all tokens from `tokenOwner`
// ------------------------------------------------------------------------
function nullifyFrom(address tokenOwner) public onlyOwner returns (bool success) {
return returnFrom(tokenOwner, balances[tokenOwner]);
}
}
contract CSTK_CLT is CSTKDropToken('CSTK_CLT', 'CryptoStock CLT Promo Token', 100000 * 10**8, 8, 0x2001f2A0Cf801EcFda622f6C28fb6E10d803D969) {
}
|
------------------------------------------------------------------------ public entry point for the `_checkOrder` function ------------------------------------------------------------------------
|
function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) {
return _checkOrder(customer);
}
| 1,430,066
|
pragma solidity ^0.5.1;
import "zos-lib/contracts/Initializable.sol";
import "openzeppelin-eth/contracts/access/Roles.sol";
import "./IMultiSigWallet.sol";
import "./MasterPropertyValue.sol";
/**
* @title Whitelist
* @dev Whitelist for managing accounts authorized to transfer tokens.
*/
contract Whitelist is Initializable {
using Roles for Roles.Role;
Roles.Role private _whitelisteds;
/*
* Events
*/
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
/*
* Storage
*/
IMultiSigWallet public operationAdminMultiSig;
IMultiSigWallet public basicProtectorMultiSig;
MasterPropertyValue public masterPropertyValue;
/*
* Modifiers
*/
/// @dev Requires sender to be the operation admin multisig contract.
modifier onlyOperationAdmin() {
require(operationAdminMultiSig.hasOwner(msg.sender));
_;
}
/// @dev Requires sender to be the basic owner multisig contract.
modifier onlyBasicProtectorMultiSig() {
require(address(basicProtectorMultiSig) == msg.sender);
_;
}
/// @dev Requires sender to be whitelisted.
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
/// @dev Requires that the MPV contract is not paused.
modifier mpvNotPaused() {
require(masterPropertyValue.paused() == false);
_;
}
/*
* Public functions
*/
/// @dev Initialize function set initial storage values.
/// @param _operationAdminMultiSig Address of operation admin multisig contract.
/// @param _basicProtectorMultiSig Address of basic protector multisig contract.
function initialize(
address _operationAdminMultiSig,
address _basicProtectorMultiSig,
MasterPropertyValue _masterPropertyValue
) public initializer
{
operationAdminMultiSig = IMultiSigWallet(_operationAdminMultiSig);
basicProtectorMultiSig = IMultiSigWallet(_basicProtectorMultiSig);
masterPropertyValue = _masterPropertyValue;
}
/// @dev Add account to whitelist.
/// @param account Address of account.
function addWhitelisted(address account)
public
onlyOperationAdmin
mpvNotPaused
{
_addWhitelisted(account);
}
/// @dev Add multiple accounts to whitelist.
/// @param accounts List of account addresses.
function addWhitelisteds(address[] memory accounts)
public
onlyOperationAdmin
mpvNotPaused
{
for (uint256 i = 0; i < accounts.length; i++) {
_addWhitelisted(accounts[i]);
}
}
/// @dev Remove account from whitelist.
/// @param account Address of account.
function removeWhitelisted(address account)
public
onlyBasicProtectorMultiSig
mpvNotPaused
{
_removeWhitelisted(account);
}
/// @dev Remove multiple accounts from whitelist.
/// @param accounts List of account addresses.
function removeWhitelisteds(address[] memory accounts)
public
onlyBasicProtectorMultiSig
mpvNotPaused
{
for (uint256 i = 0; i < accounts.length; i++) {
_removeWhitelisted(accounts[i]);
}
}
/// @dev Remove sender from whitelist.
function renounceWhitelisted()
public
mpvNotPaused
{
_removeWhitelisted(msg.sender);
}
/// @dev Returns true if account is whitelisted. Transaction can be sent by anyone.
/// @param account Address of account.
/// @return whitelisted boolean.
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
/*
* Internal functions
*/
/// @dev Add account to whitelist.
/// @param account Address of account.
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
/// @dev Remove account to whitelist.
/// @param account Address of account.
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
|
Add multiple accounts to whitelist. accounts List of account addresses.
|
function addWhitelisteds(address[] memory accounts)
public
onlyOperationAdmin
mpvNotPaused
{
for (uint256 i = 0; i < accounts.length; i++) {
_addWhitelisted(accounts[i]);
}
}
| 13,119,411
|
./full_match/5/0xed5b1D2f7904254A3d687703b6A336b538b7ddD2/sources/contracts/StableCoin.sol
|
User approves all funds to be managed by staking contract
|
function approveAll(address spender) public returns (bool) {
address owner = _msgSender();
uint256 amount = type(uint256).max;
_approve(owner, spender, amount);
return true;
}
| 1,952,254
|
./partial_match/3/0xE333bacb250b1aDC74074d4DBf13662c6Bd96172/sources/GoldenGoose.sol
|
return locking status userAddress address of to check return locking status in true or false/
|
function getLockingStatus(address userAddress) external view returns(bool){
if (now < time[userAddress]){
return true;
}
else{
return false;
}
}
| 5,077,815
|
pragma solidity ^0.5.6;
import "../storage/LinkdropFactoryStorage.sol";
import "../interfaces/ILinkdropCommon.sol";
import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract LinkdropFactoryCommon is LinkdropFactoryStorage {
using SafeMath for uint;
/**
* @dev Indicates whether a proxy contract for linkdrop master is deployed or not
* @param _linkdropMaster Address of linkdrop master
* @return True if deployed
*/
function isDeployed(address _linkdropMaster) public view returns (bool) {
return (deployed[_linkdropMaster] != address(0));
}
/**
* @dev Indicates whether a link is claimed or not
* @param _linkdropMaster Address of lindkrop signer
* @param _linkId Address corresponding to link key
* @return True if claimed
*/
function isClaimedLink(address payable _linkdropMaster, address _linkId) public view returns (bool) {
if (!isDeployed(_linkdropMaster)) {
return false;
}
else {
address payable proxy = address(uint160(deployed[_linkdropMaster]));
return ILinkdropCommon(proxy).isClaimedLink(_linkId);
}
}
/**
* @dev Function to deploy a proxy contract for msg.sender
* @return Proxy contract address
*/
function deployProxy()
public
returns (address payable)
{
address payable proxy = _deployProxy(msg.sender);
return proxy;
}
/**
* @dev Internal function to deploy a proxy contract for linkdrop master
* @param _linkdropMaster Address of linkdrop master
* @return Proxy contract address
*/
function _deployProxy(address payable _linkdropMaster)
internal
returns (address payable)
{
require(!isDeployed(_linkdropMaster), "Deployed");
require(_linkdropMaster != address(0), "Invalid linkdrop master address");
bytes32 salt = keccak256(abi.encodePacked(_linkdropMaster));
bytes memory initcode = getInitcode();
address payable proxy;
assembly {
proxy := create2(0, add(initcode, 0x20), mload(initcode), salt)
if iszero(extcodesize(proxy)) { revert(0, 0) }
}
deployed[_linkdropMaster] = proxy;
// Initialize owner address, linkdrop master address and master copy version in proxy contract
require
(
ILinkdropCommon(proxy).initialize
(
address(this), // Owner address
_linkdropMaster, // Linkdrop master address
masterCopyVersion,
chainId
),
"Failed to initialize"
);
emit Deployed(_linkdropMaster, proxy, salt, now);
return proxy;
}
/**
* @dev Function to destroy proxy contract, called by proxy owner
* @return True if destroyed successfully
*/
function destroyProxy()
public
returns (bool)
{
address payable proxyOwner = msg.sender;
require(isDeployed(proxyOwner), "Not deployed");
address payable proxy = address(uint160(deployed[proxyOwner]));
ILinkdropCommon(proxy).destroy();
delete deployed[proxyOwner];
emit Destroyed(proxyOwner, proxy, now);
return true;
}
/**
* @dev Function to get bootstrap initcode for generating repeatable contract addresses
* @return Static bootstrap initcode
*/
function getInitcode()
public view
returns (bytes memory)
{
return _initcode;
}
/**
* @dev Function to fetch the actual contract bytecode to install. Called by proxy when executing initcode
* @return Contract bytecode to install
*/
function getBytecode()
public view
returns (bytes memory)
{
return _bytecode;
}
/**
* @dev Function to set new master copy and update contract bytecode to install. Can only be called by factory owner
* @param _masterCopy Address of linkdrop mastercopy contract to calculate bytecode from
* @return True if updated successfully
*/
function setMasterCopy(address payable _masterCopy)
public returns (bool)
{
require(msg.sender == owner, "Only factory owner");
require(_masterCopy != address(0), "Invalid master copy address");
masterCopyVersion = masterCopyVersion.add(1);
require
(
ILinkdropCommon(_masterCopy).initialize
(
address(0), // Owner address
address(0), // Linkdrop master address
masterCopyVersion,
chainId
),
"Failed to initialize"
);
bytes memory bytecode = abi.encodePacked
(
hex"363d3d373d3d3d363d73",
_masterCopy,
hex"5af43d82803e903d91602b57fd5bf3"
);
_bytecode = bytecode;
emit SetMasterCopy(_masterCopy, masterCopyVersion, now);
return true;
}
/**
* @dev Function to fetch the master copy version installed (or to be installed) to proxy
* @return Master copy version
*/
function getProxyMasterCopyVersion(address _linkdropMaster) external view returns (uint) {
if (!isDeployed(_linkdropMaster)) {
return masterCopyVersion;
}
else {
address payable proxy = address(uint160(deployed[_linkdropMaster]));
return ILinkdropCommon(proxy).getMasterCopyVersion();
}
}
}
|
Indicates whether a proxy contract for linkdrop master is deployed or not _linkdropMaster Address of linkdrop master return True if deployed/
|
function isDeployed(address _linkdropMaster) public view returns (bool) {
return (deployed[_linkdropMaster] != address(0));
}
| 13,141,171
|
./full_match/1/0x12cf91718F530714def56EdC6c4b23E66E765b67/sources/contracts/protocol/vault/GeneralVault.sol
|
Deposits an `amount` of asset as collateral to borrow other asset. _asset The asset address for collateral _asset = 0x0000000000000000000000000000000000000000 means to use ETH as collateral _amount The deposit amount/ asset = ERC20 asset = ETH
|
function depositCollateral(address _asset, uint256 _amount) external payable virtual {
if (_asset != address(0)) {
require(msg.value == 0, Errors.VT_COLLATERAL_DEPOSIT_INVALID);
require(msg.value == _amount, Errors.VT_COLLATERAL_DEPOSIT_REQUIRE_ETH);
}
_stAsset,
_stAssetAmount,
msg.sender,
0
);
emit DepositCollateral(_asset, msg.sender, _amount);
}
| 4,941,491
|
./full_match/80001/0x7d5AD5F4D92Fb9d22D7E506b1570d0741EE4d783/sources/src/Contract.sol
|
Add a wallet address to an existing contact Add the wallet to the contact
|
function addWalletToContact(string memory _name, address _wallet) public onlyOwner {
contacts[_name].wallets.push(_wallet);
}
| 9,498,191
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
/// @title Eleven-Yellow BOTTO token airdrop service
/// @notice Claimable token airdrop for predetermined recipients
/// @dev Merkle tree root based proof & verification for token airdrop recipients
contract BottoAirdrop is Ownable, ReentrancyGuard {
using SafeMath for uint256;
address public immutable botto;
bytes32 public immutable merkleRoot;
uint256 public immutable endsAfter;
uint256 public totalClaimed = 0;
mapping(address => bool) public claimed;
event AirdropTransfer(address to, uint256 amount);
event RecoveryTransfer(address token, uint256 amount, address recipient);
/// @param botto_ BOTTO ERC20 contract address
/// @param merkleRoot_ the merkle root used for claim verification
/// @param endsAfter_ timestamp at which the contract owner can recover all unclaimed tokens
/// @dev Expects BOTTO token contract address
/// @dev Precalculated verification merkle root is generated from airdrop participant list
/// @dev End time ensures airdrop cannot be ended before the specified timestamp
constructor(
address botto_,
bytes32 merkleRoot_,
uint256 endsAfter_
) {
botto = botto_;
merkleRoot = merkleRoot_;
endsAfter = endsAfter_;
}
/// @notice Returns airdrop tokens to claimant if merkle proof matches claimant & claim amount
/// @param proof_ the merkle tree path from leaf to root
/// @param claimant_ address of the claimant (can be any valid address, not just msg.sender)
/// @param claim_ the amount of tokens being claimed
/// @dev Proof is generated from airdrop participants list based on sha3 of packed `claimant_ claim_`
function claim(
bytes32[] memory proof_,
address payable claimant_,
uint256 claim_
) public nonReentrant {
require(claimed[claimant_] != true, "Already claimed");
require(verify(proof_, claimant_, claim_) == true, "Invalid proof");
claimed[claimant_] = true;
if (IERC20(botto).transfer(claimant_, claim_) == true) {
emit AirdropTransfer(claimant_, claim_);
}
totalClaimed = totalClaimed.add(claim_);
}
/// @notice Verifies valid claim without cost
/// @param proof_ the merkle tree path from leaf to root
/// @param claimant_ address of the claimant (can be any valid address, not just msg.sender)
/// @param claim_ the amount of tokens being claimed
/// @dev Applications can verify claims before executing
function verify(
bytes32[] memory proof_,
address claimant_,
uint256 claim_
) public view returns (bool) {
return
MerkleProof.verify(
proof_,
merkleRoot,
bytes32(keccak256(abi.encodePacked(claimant_, claim_)))
);
}
/// @notice Sweeps unrelated token spam to a specified recipient address
/// @param token_ ERC20 token address of tokens to be recovered
/// @param amount_ the amount of tokens to recover
/// @param recipient_ the address to send the recovered tokens to
/// @dev Unclaimed BOTTO tokens cannot be recovered through this function, only with end()
/// @dev Only callable by contract owner
function recover(
address token_,
uint256 amount_,
address payable recipient_
) public onlyOwner {
require(amount_ > 0, "Invalid amount");
require(address(botto) != token_, "Recover BOTTO on end");
_recover(token_, amount_, recipient_);
}
/// @notice Ends airdrop functionality
/// @param recipient_ address where re-claimed BOTTO and ETH should be sent
/// @dev After the end time, BOTTO tokens are recovered to the given recipient & contract is destroyed
function end(address payable recipient_) public onlyOwner {
require(block.timestamp > endsAfter, "Cannot end yet");
_recover(address(botto), getBalance(), recipient_);
selfdestruct(recipient_);
}
/// @notice Get balance of BOTTO tokens owned by airdrop
function getBalance() public view returns (uint256) {
return IERC20(botto).balanceOf(address(this));
}
/// @dev internal function to handle recovery of tokens
function _recover(
address token_,
uint256 amount_,
address payable recipient_
) internal {
if (amount_ > 0) {
TransferHelper.safeTransfer(token_, recipient_, amount_);
emit RecoveryTransfer(token_, amount_, recipient_);
}
}
}
|
Verifies valid claim without cost proof_ the merkle tree path from leaf to root claimant_ address of the claimant (can be any valid address, not just msg.sender) claim_ the amount of tokens being claimed Applications can verify claims before executing
|
function verify(
bytes32[] memory proof_,
address claimant_,
uint256 claim_
) public view returns (bool) {
return
MerkleProof.verify(
proof_,
merkleRoot,
bytes32(keccak256(abi.encodePacked(claimant_, claim_)))
);
}
| 6,357,411
|
./full_match/1/0x3b985118468164b310C5254b0710888dd57c7599/sources/contracts/pool/PoolMaster.sol
|
Override of the decimals function, see {IERC20Metadata-symbol} return Pool's symbol
|
function symbol()
public
view
override(ERC20Upgradeable, PoolMetadata)
returns (string memory)
{
return super.symbol();
}
| 3,086,498
|
pragma ton-solidity >=0.47.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
pragma ignoreIntOverflow;
//================================================================================
//
/// @title Subscribe Multisig Wallet
/// @author SuperArmor
/// @notice Original contract - SafeMultisig by TonLabs (https://github.com/tonlabs/ton-labs-contracts/blob/master/solidity/safemultisig/SafeMultisigWallet.sol)
//================================================================================
//
import "../interfaces/ISubscribeMultisig.sol";
import "../contracts/Subscription.sol";
//================================================================================
//
contract SubscribeMultisig is ISubscribeMultisig
{
//========================================
//
struct Transaction
{
uint64 id; // Transaction Id.
uint32 confirmationsMask; // Transaction confirmations from custodians.
uint8 signsRequired; // Number of required confirmations.
uint8 signsReceived; // Number of confirmations already received.
uint256 creator; // Public key of custodian queued transaction.
uint8 index; // Index of custodian.
address dest; // Destination address of gram transfer.
uint128 value; // Amount of nanograms to transfer.
uint16 sendFlags; // Flags for sending internal message (see SENDRAWMSG in TVM spec).
TvmCell payload; // Payload used as body of outbound internal message.
bool bounce; // Bounce flag for header of outbound internal message.
}
//========================================
// Constants
uint8 constant MAX_QUEUED_REQUESTS = 5;
uint64 constant EXPIRATION_TIME = 3600; // lifetime is 1 hour
uint8 constant MAX_CUSTODIAN_COUNT = 32;
uint128 constant MIN_VALUE = 1e6;
uint constant MAX_CLEANUP_TXNS = 40;
//========================================
// Send flags
uint8 constant FLAG_PAY_FWD_FEE_FROM_BALANCE = 1; // Forward fees for message will be paid from contract balance.
uint8 constant FLAG_IGNORE_ERRORS = 2; // Tells node to ignore errors in action phase while outbound messages are sent.
uint8 constant FLAG_SEND_ALL_REMAINING = 128; // Tells node to send all remaining balance.
//========================================
// Variables
uint256 m_ownerKey; // Public key of custodian who deployed a contract.
uint256 m_requestsMask; // Binary mask with custodian requests (max 32 custodians).
uint8 m_custodianCount; // Read-only custodian count, initiated in constructor.
uint8 m_defaultRequiredConfirmations; // Default number of confirmations needed to execute transaction.
mapping(uint64 => Transaction) m_transactions; // Dictionary of queued transactions waiting confirmations.
mapping(uint256 => uint8) m_custodians; // pub_key -> custodian_index: set of custodians, initiated in constructor, but values can be changed later in code.
TvmCell static _subscriptionCode;
//========================================
// Exception codes
/*
100 - message sender is not a custodian;
102 - transaction does not exist;
103 - operation is already confirmed by this custodian;
107 - input value is too low;
108 - wallet should have only one custodian;
113 - Too many requests for one custodian;
117 - invalid number of custodians;
121 - payload size is too big;
*/
/*
200 - message sender is not my subscription;
*/
//========================================
// Events
event TransferAccepted(bytes payload);
//========================================
// Runtime functions
function tvm_ctos(TvmCell cell) private pure returns (uint) {}
function tvm_tree_cell_size(uint slice) private pure returns (uint, uint) {}
//========================================
// Constructor
/// @dev Contract constructor.
/// @param owners Array of custodian keys.
/// @param reqConfirms Default number of confirmations required for executing transaction.
constructor(uint256[] owners, uint8 reqConfirms) public
{
// msg.isInternal for on-chain deployment
require((msg.pubkey() == tvm.pubkey()) || (msg.isInternal && owners[0] == tvm.pubkey()), 100);
require(owners.length > 0 && owners.length <= MAX_CUSTODIAN_COUNT, 117);
tvm.accept();
uint8 ownerCount = 0;
m_ownerKey = owners[0];
for(uint256 key : owners)
{
if (!m_custodians.exists(key))
{
m_custodians[key] = ownerCount++;
}
}
m_defaultRequiredConfirmations = (ownerCount <= reqConfirms ? ownerCount : reqConfirms);
m_custodianCount = ownerCount;
}
//========================================
// Inline helper macros
/// @dev Returns queued transaction count by custodian with defined index.
function _getMaskValue(uint256 mask, uint8 index) inline private pure returns (uint8)
{
return uint8((mask >> (8 * uint256(index))) & 0xFF);
}
/// @dev Increment queued transaction count by custodian with defined index.
function _incMaskValue(uint256 mask, uint8 index) inline private pure returns (uint256)
{
return mask + (1 << (8 * uint256(index)));
}
/// @dev Decrement queued transaction count by custodian with defined index.
function _decMaskValue(uint256 mask, uint8 index) inline private pure returns (uint256)
{
return mask - (1 << (8 * uint256(index)));
}
/// @dev Checks bit with defined index in the mask.
function _checkBit(uint32 mask, uint8 index) inline private pure returns (bool)
{
return (mask & (uint32(1) << index)) != 0;
}
/// @dev Checks if object is confirmed by custodian.
function _isConfirmed(uint32 mask, uint8 custodianIndex) inline private pure returns (bool)
{
return _checkBit(mask, custodianIndex);
}
/// @dev Sets custodian confirmation bit in the mask.
function _setConfirmed(uint32 mask, uint8 custodianIndex) inline private pure returns (uint32)
{
mask |= (uint32(1) << custodianIndex);
return mask;
}
/// @dev Checks that custodian with supplied public key exists in custodian set.
function _findCustodian(uint256 senderKey) inline private view returns (uint8)
{
require(m_custodians.exists(senderKey), 100);
return(m_custodians[senderKey]);
}
/// @dev Generates new id for object.
function _generateId() inline private pure returns (uint64)
{
return (uint64(now) << 32) | (tx.timestamp & 0xFFFFFFFF);
}
/// @dev Returns timestamp after which transactions are treated as expired.
function _getExpirationBound() inline private pure returns (uint64)
{
return (uint64(now) - EXPIRATION_TIME) << 32;
}
/// @dev Returns transfer flags according to input value and `allBalance` flag.
function _getSendFlags(uint128 value, bool allBalance) inline private pure returns (uint8, uint128)
{
uint8 flags = FLAG_IGNORE_ERRORS | FLAG_PAY_FWD_FEE_FROM_BALANCE;
if(allBalance)
{
flags = FLAG_IGNORE_ERRORS | FLAG_SEND_ALL_REMAINING;
value = uint128(address(this).balance);
}
return (flags, value);
}
//========================================
// Public functions
/// @dev A payable method for accepting incoming funds. Generates
/// an event with incoming payload.
/// @param payload Payload from message body.
function acceptTransfer(bytes payload) external override
{
emit TransferAccepted(payload);
}
/// @dev Allows custodian if she is the only owner of multisig to transfer funds with minimal fees.
/// @param dest Transfer target address.
/// @param value Amount of funds to transfer.
/// @param bounce Bounce flag. Set true if need to transfer funds to existing account;
/// set false to create new account.
/// @param flags `sendmsg` flags.
/// @param payload Tree of cells used as body of outbound internal message.
function sendTransaction(address dest, uint128 value, bool bounce, uint8 flags, TvmCell payload) public view override
{
require(m_custodianCount == 1, 108);
require(msg.pubkey() == m_ownerKey, 100);
tvm.accept();
dest.transfer(value, bounce, flags, payload);
}
/// @dev Allows custodian to submit and confirm new transaction.
/// @param dest Transfer target address.
/// @param value Nanograms value to transfer.
/// @param bounce Bounce flag. Set true if need to transfer grams to existing account; set false to create new account.
/// @param allBalance Set true if need to transfer all remaining balance.
/// @param payload Tree of cells used as body of outbound internal message.
/// @return transId Transaction ID.
function submitTransaction(address dest, uint128 value, bool bounce, bool allBalance, TvmCell payload) public returns (uint64 transId)
{
uint256 senderKey = msg.pubkey();
uint8 index = _findCustodian(senderKey);
require(value >= MIN_VALUE, 107);
(uint bits, uint cells) = tvm_tree_cell_size(tvm_ctos(payload));
require(bits < 8192 && cells < 8, 121);
_removeExpiredTransactions();
require(_getMaskValue(m_requestsMask, index) < MAX_QUEUED_REQUESTS, 113);
tvm.accept();
(uint8 flags, uint128 realValue) = _getSendFlags(value, allBalance);
uint8 requiredSigns = m_defaultRequiredConfirmations;
if (requiredSigns == 1)
{
dest.transfer(realValue, bounce, flags, payload);
return 0;
}
else
{
m_requestsMask = _incMaskValue(m_requestsMask, index);
uint64 trId = _generateId();
Transaction txn = Transaction(trId, 0/*mask*/, requiredSigns, 0/*signsReceived*/,
senderKey, index, dest, realValue, flags, payload, bounce);
_confirmTransaction(trId, txn, index);
return trId;
}
}
/// @dev Allows custodian to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint64 transactionId) public
{
uint8 index = _findCustodian(msg.pubkey());
_removeExpiredTransactions();
optional(Transaction) txn = m_transactions.fetch(transactionId);
require(txn.hasValue(), 102);
require(!_isConfirmed(txn.get().confirmationsMask, index), 103);
tvm.accept();
_confirmTransaction(transactionId, txn.get(), index);
}
//========================================
//Internal functions
/// @dev Confirms transaction by custodian with defined index.
/// @param transactionId Transaction id to confirm.
/// @param txn Transaction object to confirm.
/// @param custodianIndex Index of custodian.
function _confirmTransaction(uint64 transactionId, Transaction txn, uint8 custodianIndex) inline private
{
if ((txn.signsReceived + 1) >= txn.signsRequired)
{
txn.dest.transfer(txn.value, txn.bounce, txn.sendFlags, txn.payload);
m_requestsMask = _decMaskValue(m_requestsMask, txn.index);
delete m_transactions[transactionId];
}
else
{
txn.confirmationsMask = _setConfirmed(txn.confirmationsMask, custodianIndex);
txn.signsReceived++;
m_transactions[transactionId] = txn;
}
}
/// @dev Removes expired transactions from storage.
function _removeExpiredTransactions() inline private
{
uint64 marker = _getExpirationBound();
uint i = 0;
for((uint64 trId, Transaction txn) : m_transactions)
{
bool needCleanup = trId <= marker;
if (!needCleanup) { return; }
tvm.accept();
if(!needCleanup || i >= MAX_CLEANUP_TXNS)
{
return;
}
m_requestsMask = _decMaskValue(m_requestsMask, txn.index);
delete m_transactions[trId];
}
}
//========================================
// Get methods
/// @dev Helper get-method for checking if custodian confirmation bit is set.
/// @return confirmed True if confirmation bit is set.
function isConfirmed(uint32 mask, uint8 index) public pure returns (bool confirmed)
{
confirmed = _isConfirmed(mask, index);
}
/// @dev Get-method that returns wallet configuration parameters.
/// @return maxQueuedTransactions The maximum number of unconfirmed transactions that a custodian can submit.
/// @return maxCustodianCount The maximum allowed number of wallet custodians.
/// @return expirationTime Transaction lifetime in seconds.
/// @return minValue The minimum value allowed to transfer in one transaction.
/// @return requiredTxnConfirms The minimum number of confirmations required to execute transaction.
function getParameters() public view returns (uint8 maxQueuedTransactions, uint8 maxCustodianCount, uint64 expirationTime, uint128 minValue, uint8 requiredTxnConfirms)
{
maxQueuedTransactions = MAX_QUEUED_REQUESTS;
maxCustodianCount = MAX_CUSTODIAN_COUNT;
expirationTime = EXPIRATION_TIME;
minValue = MIN_VALUE;
requiredTxnConfirms = m_defaultRequiredConfirmations;
}
/// @dev Get-method that returns transaction info by id.
/// @return trans Transaction structure.
/// Throws exception if transaction does not exist.
function getTransaction(uint64 transactionId) public view returns (Transaction trans)
{
require(m_transactions.exists(transactionId), 102);
trans = m_transactions[transactionId];
}
/// @dev Get-method that returns array of pending transactions.
/// Returns not expired transactions only.
/// @return transactions Array of queued transactions.
function getTransactions() public view returns (Transaction[] transactions)
{
uint64 bound = _getExpirationBound();
for((uint64 id, Transaction txn) : m_transactions)
{
if (id > bound)
{
transactions.push(txn);
}
}
}
/// @dev Get-method that returns submitted transaction ids.
/// @return ids Array of transaction ids.
function getTransactionIds() public view returns (uint64[] ids)
{
for((uint64 trId, ) : m_transactions)
{
ids.push(trId);
}
}
/// @dev Helper structure to return information about custodian.
/// Used in getCustodians().
struct CustodianInfo
{
uint8 index;
uint256 pubkey;
}
/// @dev Get-method that returns info about wallet custodians.
/// @return custodians Array of custodians.
function getCustodians() public view returns (CustodianInfo[] custodians)
{
for((uint256 key, uint8 index) : m_custodians)
{
custodians.push(CustodianInfo(index, key));
}
}
//========================================
// Fallback and receive functions to receive simple transfers.
fallback() external {}
receive () external {}
//========================================
// Subscription functions
function calculateFutureSubscriptionAddress(address serviceAddress) private inline view returns (address, TvmCell)
{
TvmCell stateInit = tvm.buildStateInit({
contr: Subscription,
varInit: {
_walletAddress: address(this),
_serviceAddress: serviceAddress
},
code: _subscriptionCode
});
return (address(tvm.hash(stateInit)), stateInit);
}
//========================================
// Current implementation requires only one custodian ownership to create a subscription;
// Multi-custodian Multisigs are not supported, but can be in the future.
function createSubscription(address serviceAddress, uint256 planID, uint32 period, uint128 periodPrice) external override
{
require(m_custodianCount == 1, 108);
require(msg.pubkey() == m_ownerKey, 100);
tvm.accept();
(address subscriptionAddress, TvmCell stateInit) = calculateFutureSubscriptionAddress(serviceAddress);
new Subscription{value: gasToValue(500000, address(this).wid), bounce: false, stateInit: stateInit}();
ISubscription(subscriptionAddress).createSubscription{value: periodPrice, flag: 1}(planID, period, periodPrice);
}
function subscriptionPaymentRequested(address serviceAddress, uint128 periodPrice) external override
{
(address subscriptionAddress, ) = calculateFutureSubscriptionAddress(serviceAddress);
require(msg.sender == subscriptionAddress, 200);
tvm.accept();
ISubscription(subscriptionAddress).payForSubscription{value: periodPrice, bounce: true, flag: 64+1}(); // We will bounce if there's not enough balance, this is expected; Subscription will catch the bounce.
}
}
//================================================================================
//
|
Generates new id for object.
|
function _generateId() inline private pure returns (uint64)
{
return (uint64(now) << 32) | (tx.timestamp & 0xFFFFFFFF);
}
| 2,526,841
|
pragma solidity ^0.5.8;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface IERC20 {
function TOTALSUPPLY24() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF234(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER72(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE257(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE45(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM346(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER728(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL558(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME136() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL217() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS964() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
library SafeMath {
function ADD825(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB689(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL868(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, "SafeMath: multiplication overflow");
return c;
}
function DIV452(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD717(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY24() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF234(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER72(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER437(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE257(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE45(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE89(msg.sender, spender, value);
return true;
}
function TRANSFERFROM346(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER437(sender, recipient, amount);
_APPROVE89(sender, msg.sender, _allowances[sender][msg.sender].SUB689(amount));
return true;
}
function INCREASEALLOWANCE86(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE89(msg.sender, spender, _allowances[msg.sender][spender].ADD825(addedValue));
return true;
}
function DECREASEALLOWANCE981(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE89(msg.sender, spender, _allowances[msg.sender][spender].SUB689(subtractedValue));
return true;
}
function _TRANSFER437(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB689(amount);
_balances[recipient] = _balances[recipient].ADD825(amount);
emit TRANSFER728(sender, recipient, amount);
}
function _MINT126(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD825(amount);
_balances[account] = _balances[account].ADD825(amount);
emit TRANSFER728(address(0), account, amount);
}
function _BURN761(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.SUB689(value);
_balances[account] = _balances[account].SUB689(value);
emit TRANSFER728(account, address(0), value);
}
function _APPROVE89(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit APPROVAL558(owner, spender, value);
}
function _BURNFROM912(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN761(account, amount);
_APPROVE89(account, msg.sender, _allowances[account][msg.sender].SUB689(amount));
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function ADD825(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(!HAS200(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
function REMOVE879(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(HAS200(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
function HAS200(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MINTERADDED281(address indexed account); //inject NONSTANDARD NAMING
event MINTERREMOVED788(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _minters;
constructor () internal {
_ADDMINTER695(msg.sender);
}
modifier ONLYMINTER448() { //inject NONSTANDARD NAMING
require(ISMINTER103(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function ISMINTER103(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _minters.HAS200(account);
}
function ADDMINTER340(address account) public ONLYMINTER448 { //inject NONSTANDARD NAMING
_ADDMINTER695(account);
}
function RENOUNCEMINTER82() public { //inject NONSTANDARD NAMING
_REMOVEMINTER969(msg.sender);
}
function _ADDMINTER695(address account) internal { //inject NONSTANDARD NAMING
_minters.ADD825(account);
emit MINTERADDED281(account);
}
function _REMOVEMINTER969(address account) internal { //inject NONSTANDARD NAMING
_minters.REMOVE879(account);
emit MINTERREMOVED788(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
contract ERC20Mintable is ERC20, MinterRole {
function MINT699(address account, uint256 amount) public ONLYMINTER448 returns (bool) { //inject NONSTANDARD NAMING
_MINT126(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP280() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _MINT126(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(TOTALSUPPLY24().ADD825(value) <= _cap, "ERC20Capped: cap exceeded");
super._MINT126(account, value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
contract ERC20Burnable is ERC20 {
function BURN558(uint256 amount) public { //inject NONSTANDARD NAMING
_BURN761(msg.sender, amount);
}
function BURNFROM709(address account, uint256 amount) public { //inject NONSTANDARD NAMING
_BURNFROM912(account, amount);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED785(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED785(address(0), _owner);
}
function OWNER790() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER785() { //inject NONSTANDARD NAMING
require(ISOWNER48(), "Ownable: caller is not the owner");
_;
}
function ISOWNER48() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP92() public ONLYOWNER785 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED785(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP413(address newOwner) public ONLYOWNER785 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP978(newOwner);
}
function _TRANSFEROWNERSHIP978(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED785(_owner, newOwner);
_owner = newOwner;
}
}
// File: eth-token-recover/contracts/TokenRecover.sol
contract TokenRecover is Ownable {
function RECOVERERC20723(address tokenAddress, uint256 tokenAmount) public ONLYOWNER785 { //inject NONSTANDARD NAMING
IERC20(tokenAddress).TRANSFER72(OWNER790(), tokenAmount);
}
}
// File: ico-maker/contracts/access/roles/OperatorRole.sol
contract OperatorRole {
using Roles for Roles.Role;
event OPERATORADDED875(address indexed account); //inject NONSTANDARD NAMING
event OPERATORREMOVED255(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _operators;
constructor() internal {
_ADDOPERATOR101(msg.sender);
}
modifier ONLYOPERATOR594() { //inject NONSTANDARD NAMING
require(ISOPERATOR640(msg.sender));
_;
}
function ISOPERATOR640(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _operators.HAS200(account);
}
function ADDOPERATOR763(address account) public ONLYOPERATOR594 { //inject NONSTANDARD NAMING
_ADDOPERATOR101(account);
}
function RENOUNCEOPERATOR674() public { //inject NONSTANDARD NAMING
_REMOVEOPERATOR451(msg.sender);
}
function _ADDOPERATOR101(address account) internal { //inject NONSTANDARD NAMING
_operators.ADD825(account);
emit OPERATORADDED875(account);
}
function _REMOVEOPERATOR451(address account) internal { //inject NONSTANDARD NAMING
_operators.REMOVE879(account);
emit OPERATORREMOVED255(account);
}
}
// File: ico-maker/contracts/token/ERC20/BaseERC20Token.sol
contract BaseERC20Token is ERC20Detailed, ERC20Capped, ERC20Burnable, OperatorRole, TokenRecover {
event MINTFINISHED767(); //inject NONSTANDARD NAMING
event TRANSFERENABLED385(); //inject NONSTANDARD NAMING
// indicates if minting is finished
bool private _mintingFinished = false;
// indicates if transfer is enabled
bool private _transferEnabled = false;
modifier CANMINT798() { //inject NONSTANDARD NAMING
require(!_mintingFinished);
_;
}
modifier CANTRANSFER140(address from) { //inject NONSTANDARD NAMING
require(_transferEnabled || ISOPERATOR640(from));
_;
}
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
uint256 initialSupply
)
public
ERC20Detailed(name, symbol, decimals)
ERC20Capped(cap)
{
if (initialSupply > 0) {
_MINT126(OWNER790(), initialSupply);
}
}
function MINTINGFINISHED780() public view returns (bool) { //inject NONSTANDARD NAMING
return _mintingFinished;
}
function TRANSFERENABLED7() public view returns (bool) { //inject NONSTANDARD NAMING
return _transferEnabled;
}
function MINT699(address to, uint256 value) public CANMINT798 returns (bool) { //inject NONSTANDARD NAMING
return super.MINT699(to, value);
}
function TRANSFER72(address to, uint256 value) public CANTRANSFER140(msg.sender) returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER72(to, value);
}
function TRANSFERFROM346(address from, address to, uint256 value) public CANTRANSFER140(from) returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM346(from, to, value);
}
function FINISHMINTING211() public ONLYOWNER785 CANMINT798 { //inject NONSTANDARD NAMING
_mintingFinished = true;
emit MINTFINISHED767();
}
function ENABLETRANSFER141() public ONLYOWNER785 { //inject NONSTANDARD NAMING
_transferEnabled = true;
emit TRANSFERENABLED385();
}
function REMOVEOPERATOR532(address account) public ONLYOWNER785 { //inject NONSTANDARD NAMING
_REMOVEOPERATOR451(account);
}
function REMOVEMINTER389(address account) public ONLYOWNER785 { //inject NONSTANDARD NAMING
_REMOVEMINTER969(account);
}
}
// File: contracts/ERC20Token.sol
contract ERC20Token is BaseERC20Token {
string public builtOn = "https://vittominacori.github.io/erc20-generator";
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
uint256 initialSupply
)
public
BaseERC20Token(name, symbol, decimals, cap, initialSupply)
{} // solhint-disable-line no-empty-blocks
}
|
inject NONSTANDARD NAMING
|
function _ADDOPERATOR101(address account) internal {
| 2,480,335
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract FundMe {
// TYPES
struct Funder {
bool isFunder;
uint256 amountFunded;
uint256 index;
}
// VARIABLES
address public m_Owner;
address[] public m_Funders;
uint256 m_entranceFeeUSD = 50;
AggregatorV3Interface public m_PriceFeed;
mapping(address => Funder) public m_AddressToFunderData;
// MODIFIERS
modifier onlyOwner() {
require(
msg.sender == m_Owner,
"Only the owner of the contract can run this function"
);
_; // Resume
}
modifier onlyFunder() {
require(
this._isFunder(msg.sender),
"Only funders of the contract can run this function"
);
_; // Resume
}
// METHODS
constructor(address _priceFeedAddress) {
m_PriceFeed = AggregatorV3Interface(_priceFeedAddress);
m_Owner = msg.sender;
}
function fund() public payable {
// Comparison is made in GWEI unit.
require(
msg.value >= this._getEntranceFee(),
"Try spending more $ETH !"
);
// Add funder to data if first time
if (this._isFunder(msg.sender) == false) {
m_Funders.push(msg.sender);
m_AddressToFunderData[msg.sender] = Funder({
isFunder: true,
amountFunded: 0,
index: m_Funders.length - 1
});
}
m_AddressToFunderData[msg.sender].amountFunded += msg.value;
}
function withdrawWei(uint256 _amount) public onlyFunder {
// Checks if the contract has enough funds, if not : BIG EXPLOIT.
require(
address(this).balance >= _amount,
"Contract : Insufficient funds"
);
// Checks if the funder has enough funds to withdraw _amount.
require(
m_AddressToFunderData[msg.sender].amountFunded >= _amount,
"You cannot withdraw more than the amount you have founded."
);
payable(msg.sender).transfer(_amount);
m_AddressToFunderData[msg.sender].amountFunded -= _amount;
if (m_AddressToFunderData[msg.sender].amountFunded == 0) {
delete (m_Funders[m_AddressToFunderData[msg.sender].index]);
delete (m_AddressToFunderData[msg.sender]);
}
}
function withdrawGwei(uint256 _amount) public {
this.withdrawWei(_amount * 10**9);
}
function withdrawEth(uint256 _amount) public {
this.withdrawWei(_amount * 10**18);
}
function _setEntranceFee(uint256 _newEntranceFeeUSD) public onlyOwner {
// Sets the entrance fee in USD
m_entranceFeeUSD = _newEntranceFeeUSD;
}
function _setPriceFeedAddress(address _address) public onlyOwner {
m_PriceFeed = AggregatorV3Interface(_address);
}
// Returns the minimum USD amount in WEI (or ETH with a precision of 18)
// to create a successful fund transaction.
function _getEntranceFee() public view returns (uint256) {
uint256 ethPrice = this._getPrice();
// uint256 ethPricePrecision = 10**8;
// uint256 weiPrecision = 10**18;
// uint256 totalPrecision = ethPricePrecision * weiPrecision;
uint256 totalPrecision = 10**26;
return ((m_entranceFeeUSD * totalPrecision) / ethPrice);
}
// Gets ETH price in USD with a precision of 8
function _getPrice() public view returns (uint256) {
(, int256 answer, , , ) = m_PriceFeed.latestRoundData();
return uint256(answer);
}
// Converts WEI to USD with a precision of 8.
// Parameter weiAmount has a precision of 18.
function _weiToUsd(uint256 weiAmount) public view returns (uint256) {
// Precision of 8 applied to ethPrice.
uint256 ethPrice = this._getPrice();
// Divide by (10^10) * (10^8) == (10^18) -> Keeps a precision of 8.
uint256 usdValue = (ethPrice * weiAmount) / (10**18);
return usdValue;
}
function _gweiToUsd(uint256 gweiAmount) public view returns (uint256) {
return this._weiToUsd(gweiAmount * (10**9));
}
function _ethToUsd(uint256 ethAmount) public view returns (uint256) {
return this._weiToUsd(ethAmount * (10**18));
}
function _isFunder(address _address) public view returns (bool) {
return m_AddressToFunderData[_address].isFunder;
}
function _getVersion() public view returns (uint256) {
return m_PriceFeed.version();
}
}
|
Comparison is made in GWEI unit. Add funder to data if first time
|
function fund() public payable {
require(
msg.value >= this._getEntranceFee(),
"Try spending more $ETH !"
);
if (this._isFunder(msg.sender) == false) {
m_Funders.push(msg.sender);
m_AddressToFunderData[msg.sender] = Funder({
isFunder: true,
amountFunded: 0,
index: m_Funders.length - 1
});
}
m_AddressToFunderData[msg.sender].amountFunded += msg.value;
}
| 6,411,196
|
// SPDX-License-Identifier: MIT
// ------------------------------------------------------------------------
// MIT License
// Copyright (c) 2020 candleo.money
//
// 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.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account)
internal
pure
returns (address payable)
{
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(
value
);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
// address payable public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
pragma solidity ^0.5.0;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(
uint256 rate,
address payable wallet,
IERC20 token
) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(
address(token) != address(0),
"Crowdsale: token is the zero address"
);
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function() external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public payable nonReentrant {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount)
internal
view
{
require(
beneficiary != address(0),
"Crowdsale: beneficiary is the zero address"
);
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @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.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @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);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant {
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
/**
@title PreSaleTwo
@dev This is an example of a fully fledged crowdsale.
*/
contract LEOCrowdsale2 is Crowdsale {
constructor(
uint256 rate,
address payable wallet,
IERC20 token
) public Crowdsale(rate, wallet, token) {}
}
|
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
|
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
);
}
| 34,646
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.